不正确的标题检查在node.js中使用zlib时

我想发送一个简单的HTTP POST请求,检索响应body.Following是我的代码。 我正进入(状态

错误:错误的标题检查

在“zlib.gunzip”方法中。 我是新的node.js,我感谢任何帮助。

;

fireRequest: function() { var rBody = ''; var resBody = ''; var contentLength; var options = { 'encoding' : 'utf-8' }; rBody = fSystem.readFileSync('resources/im.json', options); console.log('Loaded data from im.json ' + rBody); contentLength = Buffer.byteLength(rBody, 'utf-8'); console.log('Byte length of the request body ' + contentLength); var httpOptions = { hostname : 'abc.com', path : '/path', method : 'POST', headers : { 'Authorization' : 'Basic VHJhZasfasNWEWFScsdfsNCdXllcjE6dHJhZGVjYXJk', 'Content-Type' : 'application/json; charset=UTF=8', // 'Accept' : '*/*', 'Accept-Encoding' : 'gzip,deflate,sdch', 'Content-Length' : contentLength } }; var postRequest = http.request(httpOptions, function(response) { var chunks = ''; console.log('Response received'); console.log('STATUS: ' + response.statusCode); console.log('HEADERS: ' + JSON.stringify(response.headers)); // response.setEncoding('utf8'); response.setEncoding(null); response.on('data', function(res) { chunks += res; }); response.on('end', function() { var encoding = response.headers['content-encoding']; if (encoding == 'gzip') { zlib.gunzip(chunks, function(err, decoded) { if (err) throw err; console.log('Decoded data: ' + decoded); }); } }); }); postRequest.on('error', function(e) { console.log('Error occured' + e); }); postRequest.write(rBody); postRequest.end(); } 

response.on('data', ...)可以接受一个Buffer ,不只是普通的string。 当连接你正在转换为string不正确,然后再不能gunzip。 你有2个选项:

1)收集数组中的所有缓冲区,并在end事件中使用Buffer.concat()将它们Buffer.concat() 。 然后打电话给gunzip的结果。

2)使用.pipe()并将响应传递给一个gunzip对象,如果你想在内存中得到结果,把它的输出传输到文件stream或string/缓冲区string。

这两个选项(1)和(2)在这里讨论: http : //nickfishman.com/post/49533681471/nodejs-http-requests-with-gzip-deflate-compression