node https 和 zlib 包:无法解析来自 stackoverflow.com 的 gzip 响应

问题描述 投票:0回答:1

gunzip 响应不起作用(我肯定得到了 gzip 响应),标头不正确,我真的不明白为什么。下面是演示代码:

const https = require('https')
const zlib = require('zlib')

const options = {
  headers: {
    'Accept-Encoding': 'gzip'
  },
}

https.get('https://stackoverflow.com/', options, resp => {
  let data = "";
  resp.on("data", chunk => {
    data += chunk;
  });

  resp.on("end", () => {
    if (resp.headers['content-encoding'] != 'gzip') {
      console.log('should get gzip')
      process.exit(1)
    }
    console.log('got gzip!')
    zlib.gunzip(data, data_ungzip => {
      console.log(data_ungzip)
    })
  });
})

输出:

got gzip!
Error: incorrect header check
    at Zlib.zlibOnError [as onerror] (zlib.js:187:17) {
  errno: -3,
  code: 'Z_DATA_ERROR'
}
node.js http https zlib
1个回答
0
投票

gzip 压缩的响应在转换为字符串

data
期间被损坏。以下作品:

const resp_uncompressed = resp.pipe(zlib.createGunzip());
resp_uncompressed.on("data", ...);
resp_uncompressed.on("end", ...);
© www.soinside.com 2019 - 2024. All rights reserved.