【问题标题】:Why does this GET request seem to give random characters?为什么这个 GET 请求似乎给出了随机字符?
【发布时间】:2022-03-12 00:28:05
【问题描述】:

这是我第一次使用 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。

【问题讨论】:

  • 你可能想要一个更高级别的库,比如node-fetch
  • 你能说明同样的请求对curl 有什么作用吗?它实际上返回了什么。数据很少是随机的。这可能是一些二进制文件,但很难用你迄今为止分享的内容来说明。
  • 卷曲?那是另一个 node.js 包吗?
  • 无论哪种方式 - 据我们所知,您的 valid url 是一个随机字符串生成器。此外,您还需要查看响应标头。如果上面写着content-encoding: gzip,那就是压缩了……
  • 内容看起来被压缩了。我也怀疑gzip。 This might help

标签: javascript html node.js http


【解决方案1】:

正如@Jamestheir comment 中所说,内容已被压缩。这样做很有效:

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
    })
})

【讨论】:

    猜你喜欢
    • 2014-02-02
    • 2014-01-08
    • 2011-02-05
    • 2014-04-08
    • 2015-05-16
    • 2017-09-21
    • 2018-11-22
    • 2017-06-05
    • 1970-01-01
    相关资源
    最近更新 更多