也许您的麻烦在于
'Accept-Encoding'标题。假设您的标题为
'Accept-Encoding': 'gzip,deflate'
如果是这样,您有2种方法可以解决此问题:
- 删除此标题
- 使用以下代码解压缩数据:
const req = request(options, res => {let buffers = []let bufferLength = 0let strings = []const getData = chunk => { if (!Buffer.isBuffer(chunk)) { strings.push(chunk) } else if (chunk.length) { bufferLength += chunk.length buffers.push(chunk) }}const endData = () => { let response = {pre: 200, body: ''} if (bufferLength) { response.body = Buffer.concat(buffers, bufferLength) if (options.encoding !== null) { response.body = response.body.toString(options.encoding) } buffers = [] bufferLength = 0 } else if (strings.length) { if (options.encoding === 'utf8' && strings[0].length > 0 && strings[0][0] === 'uFEFF') { strings[0] = strings[0].substring(1) } response.body = strings.join('') } console.log('response', response)};switch (res.headers['content-encoding']) { // or, just use zlib.createUnzip() to handle both cases case 'gzip': res.pipe(zlib.createGunzip()) .on('data', getData) .on('end', endData) break; case 'deflate': res.pipe(zlib.createInflate()) .on('data', getData) .on('end', endData) break; default: res.pipe(zlib.createInflate()) .on('data', getData) .on('end', endData) break;}
});
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)