Javascript 如何在节点中解码gzip或utf-8响应?
我正在使用节点请求模块来执行一些get请求Javascript 如何在节点中解码gzip或utf-8响应?,javascript,node.js,utf-8,gzip,Javascript,Node.js,Utf 8,Gzip,我正在使用节点请求模块来执行一些get请求 { body: '\u001f?\b\u0000\u0000\u0000\u0000\u0000...............' } 我有这样的头参数和请求 var params = { url: options.url, headers: { 'Accept-Encoding': "gzip, deflate", 'Accept': '*
{
body: '\u001f?\b\u0000\u0000\u0000\u0000\u0000...............'
}
我有这样的头参数和请求
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');
和newbuffer(response.body,'ascii')。toString('utf8')
读取正文内容,但它不工作
如何将正文内容正确地理解为JSON?使用
zlib.createGunzip()
删除“接受编码”:“gzip,deflate”,因为您似乎得到了一个紧张的响应。我无法删除它,服务器总是“接受编码”,为什么您不能?您可以将其更改为
“接受编码”:“
。这可能会有所帮助
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();