我正在使用节点请求模块来做一些get请求。我得到了像
这样的响应体{
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');
和new Buffer(response.body, 'ascii').toString('utf8')
阅读正文内容,但无效。
如何正确读取正文内容为JSON?
答案 0 :(得分:0)
这可以使用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();