gpt4 book ai didi

javascript - 如何在 Node 中解码 gzip 或 utf-8 响应?

转载 作者:行者123 更新时间:2023-11-30 06:26:44 25 4
gpt4 key购买 nike

我正在使用 Node 请求模块做一些获取请求。我得到的响应正文如下

{
body: '\u001f?\b\u0000\u0000\u0000\u0000\u0000...............'
}

我有这样的 header 参数和请求,

var params = {
url: options.url,
headers: {
'Accept-Encoding': "gzip, deflate",
'Accept': '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'Accept-Charset' : 'utf-8',
'Content-Type' : 'application/json',
'User-Agent' : 'Mozilla/5.0'
}
};

request(params, function (error, response, body) {

//response.setEncoding('utf8');
//response.setEncoding('binary');

console.log(response);
})

我试过了

 //response.setEncoding('utf8');
//response.setEncoding('binary');

new Buffer(response.body, 'ascii').toString('utf8') 读取正文内容但它不起作用。

如何正确读取正文内容作为 JSON?

最佳答案

这可以使用 zlib.createGunzip()像这样:

var http = require("http"),
zlib = require("zlib");

var req = http.request(url, function (res) {

// pipe the response into the gunzip to decompress
var gunzip = zlib.createGunzip();
res.pipe(gunzip);

gunzip.on('data', function (data) {
// decompression chunk ready, add it to the buffer
buffer.push(data.toString());

}).on("end", function () {
// response and decompression complete, join the buffer and return
callback(null, buffer.join(""));

}).on("error", function (e) {
callback(e);
});
});

req.on('error', function (e) {
callback(e);
});

req.end();

关于javascript - 如何在 Node 中解码 gzip 或 utf-8 响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20636587/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com