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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/19438884/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 16:01:09  来源:igfitidea点击:

Incorrect Header Check when using zlib in node.js

node.jszlib

提问by Thusitha Nuwan

I am trying to send a simple HTTP POST request, retrieve the response body.Following is my code. I am getting

我正在尝试发送一个简单的 HTTP POST 请求,检索响应正文。以下是我的代码。我正进入(状态

Error: Incorrect header check

错误:不正确的标头检查

inside the "zlib.gunzip" method. I am new to node.js and I appreciate any help.

在“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();

}

回答by Nitzan Shaked

response.on('data', ...)can accept a Buffer, not just plain strings. When concatenating you are converting to string incorrectly, and then later can't gunzip. You have 2 options:

response.on('data', ...)可以接受 a Buffer,而不仅仅是普通字符串。连接时,您错误地转换为字符串,然后无法使用 gunzip。您有 2 个选择:

1) Collect all the buffers in an array, and in the endevent concatentate them using Buffer.concat(). Then call gunzip on the result.

1) 收集数组中的所有缓冲区,并在end事件中使用Buffer.concat(). 然后对结果调用 gunzip。

2) Use .pipe()and pipe the response to a gunzip object, piping the output of that to either a file stream or a string/buffer string if you want the result in memory.

2) 使用.pipe()响应并将响应通过管道传输到 gunzip 对象,如果您希望将结果保存在内存中,则将其输出传输到文件流或字符串/缓冲区字符串。

Both options (1) and (2) are discussed here: http://nickfishman.com/post/49533681471/nodejs-http-requests-with-gzip-deflate-compression

此处讨论了选项 (1) 和 (2):http: //nickfishman.com/post/49533681471/nodejs-http-requests-with-gzip-deflate-compression

回答by Roman

In our case we added 'accept-encoding': 'gzip,deflate'to the headers and code started working (solution credited to Arul Mani):

在我们的例子中,我们添加'accept-encoding': 'gzip,deflate'了标题,代码开始工作(解决方案归功于 Arul Mani):

var httpOptions = {
    hostname : 'abc.com',
    path : '/path',
    method : 'POST',
    headers : {
        ...
        'accept-encoding': 'gzip,deflate'
    }
};

回答by arnaudjnn

I had this error trying to loop with fs.readdirSyncbut there is a .Dstorefile so the unzip function was applied to it.

我在尝试循环时遇到了这个错误,fs.readdirSync但有一个.Dstore文件,因此对它应用了解压缩功能。

Be careful to pass only .zip/gz

小心只通过 .zip/gz

import gunzip from 'gunzip-file';

const unzipAll = async () => {
  try {
    const compFiles = fs.readdirSync('tmp')
    await Promise.all(compFiles.map( async file => {
      if(file.endsWith(".gz")){
        gunzip(`tmp/${file}`, `tmp/${file.slice(0, -3)}`)
      }
    }));
  }
  catch(err) {
    console.log(err)
  }
}