這是我第一次使用 https node.js 模塊,我嘗試GET使用此代碼發出請求
const url = new URL("valid url") //I did put a valid url
https.get({
host: url.hostname,
path: url.pathname,
headers: {
"Content-Type": "application/json"
}
}, (res) => {
res.setEncoding("utf8")
let str = ""
res.on("data", c => {
console.log(c)
})
res.on("end", () => {
console.log(str) //this was meant to log the data but I removed the "str = c" from the data callback
})
})
但這會記錄以下內容:
▼?
?VJ-*?/??LQ?210ЁrsS????S????3KR§2?§?R♂K3?RS?`J??sA?I?)???E@NIj?R-???g??PP
但我認為.setEncoding("utf8")會起作用。和標題有關系嗎?或者也許是URL物件?我想要的結果在一個<pre>元素中并且是有效的 JSON。
uj5u.com熱心網友回復:
正如@James在他們的評論中所說,內容被壓縮了。這樣做有效:
import https from "https"
import { createGunzip } from "zlib"
const url = new URL("valid url")
const req = https.get(url, (res) => { //I found out you can use a URL object
let str = "{}"
let output;
//See if it's compressed so we can read it properly
var gzip = createGunzip()
res.headers["content-encoding"] == "gzip" ?
output = res.pipe(gzip) :
output = res;
output.on("data", c => {
str = c.toString()
})
output.on("end", () => {
console.log(JSON.parse(str)) //logs the correct object
})
})
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/355981.html
標籤:javascript html 节点.js http
下一篇:復式記賬法-做分錄
