在POST中将GZIPed数据发送到node.js服务器时发生错误

我的Node.js服务器需要在POST请求中接收大量压缩的JSON(gzip)数据。 我已经添加了一些代码来gunzip POST的有效负载,但是结果总是不正确的,并且取决于发布的JSON的大小。

 var http = require('http'); var zlib = require('zlib'); var port = process.env.port || 1337; http.createServer(function(req, res) { if (req.method == 'POST') { if( req.headers['content-encoding'] == 'gzip' ) { var body = []; req.on('data', function (data) { console.log('Receiving data...'); body.push(data); }); req.on('end', function () { console.log('Data received! Uncompressing...'); var buffer = Buffer.concat(body); zlib.gunzip(buffer, function(err, result) { if (!err) { console.log('Unzipped!!') var r = result.toString(); console.log(r) res.writeHead(200, { 'Content-Type': 'application/json' }); res.end(r); } else { console.log(err); res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Something went wrong!'); } }); }); } else { console.log('Everything OK with uncompressed requests!'); res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Some JSON was received!\n'); } req.on('error', function(err){ console.log(err); res.writeHead(500, { 'Content-Type': 'text/plain' }); res.end('Something went wrong!'); }); } else { res.writeHead(200, { 'Content-Type': 'text/plain' }); res.end('Hello World\n'); } }).listen(1337); 

如果我发送正常,未压缩的JSON数据一切正常。

压缩结果:

当试图解压缩数据时{"id":1, "name":"Gabe"} – >返回500,错误:不正确的头检查] errno:-3,code:'Z_DATA_ERROR' 正如在评论中指出的那样,这不是不正确的行为,因为有效载荷非常小,没有被压缩。

{"id":1,"name":"Gabe","age":33,"address":"555 Road, City, Province","occupation":"I exchange code for money"} -在request.on('data'...之后,突然终止一个504,尽pipe进程继续并显示正确的未压缩数据,如下所示。

{"id":1,"name":"Gabe","age":666,"address":"666 Road, City, Province","occupation":"I sleep during the day and write code at night... not"} – >它卡住接收数据,什么都没有。

504收到数据后 - 进程继续并显示正确的有效负载

为了进行testing,我已经configurationFiddler来发送压缩数据,只要Content-Encoding标题设置为Rules – > Customize Rules :

 if (oSession.requestBodyBytes != null && oSession.requestBodyBytes.Length>50 && oSession.oRequest.headers.Exists("Content-Encoding")){ oSession.requestBodyBytes = Utilities.GzipCompress(oSession.requestBodyBytes); oSession["Content-Length"] = oSession.requestBodyBytes.Length.ToString(); oSession["Content-Encoding"] = "gzip"; } 

示例请求:

 POST http://localhost:1337/ HTTP/1.1 User-Agent: Fiddler Content-Encoding: gzip Host: localhost:1337 {"id":1,"name":"Gabe","age":00,"address":"555 Road, City, Province","occupation":"I exchange code for money"} 

我试着听错误和使用域名,但我没有看到任何生成的错误。 我也试过用Express来手动执行,并使用支持GZIP和Deflate的body-parser模块,行为也是一样的。 testing节点0.10.18和0.10.30,没有Express,最后是Express 3和4。

那么,这里发生了什么? 我真的非常盲目,我在某个地方错过了一个冒号吗? 这是节点中的错误? 这是我向小提琴手发送请求的方式吗?