我的HTTP请求有{'content-encoding':“gzip”}标头。我正在尝试使用node.js读取数据。我使用下面的代码来解压缩数据。但我得到错误:Zlib._handle.onerror(zlib.js:355:17)错误的标题检查错误:-3,代码:'Z_DATA_ERROR'。有人可以帮我纠正这个错误。
var myHttp = require("http");
var url = require("url");
var qString = require("querystring");
var fs = require('fs');
var zlib = require('zlib');
var myEvents = require('./customEvents');
var myAppWebServer = myHttp.createServer(function(request, response){
response.setHeader('Access-Control-Allow-Origin', 'http://localhost:8080');
response.setHeader('Access-Control-Allow-Methods', 'GET, POST, OPTIONS, PUT, PATCH, DELETE');
response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With,content-type');
response.setHeader('Access-Control-Allow-Credentials', true);
response.setHeader('content-type', 'application/json');
var body = "";
request.on('data', function (chunk) {
body += chunk;
});
request.on('end', function () {
if(body){
function getGzipped(url, callback) {
var buffer = [];
myHttp.get(url, function(response) {
var gunzip = zlib.createGunzip();
response.pipe(gunzip);
gunzip.on('data', function(data) {
buffer.push(data.toString());
}).on("end", function() {
callback(null, buffer.join(""));
}).on("error", function(e) {
callback(e);
})
}).on('error', function(e) {
callback(e)
});
}
getGzipped(url, function(err, data) {
console.log(err);
});
}
});
response.end('{ "links" :"http://localhost:8080/users" }');
});
myAppWebServer.listen(8080);
我在客户端尝试POST时遇到同样的错误。如果发送方在数据缓冲区上使用zlib,那么编码和标题将是“zlib”而不是“gzip”。
我将“内容编码”从“gzip”更改为“deflate”(a.k.a. zlib;有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Encoding)。
服务器开始接受我的POST。所以你的问题可能在发送端而不是解码。