使用请求进行nodejs编码

使用请求进行nodejs编码,第1张

使用请求进行nodejs编码

也许您的麻烦在于

'Accept-Encoding'
标题假设您的标题为
'Accept-Encoding': 'gzip,deflate'

如果是这样,您有2种方法可以解决此问题:

  1. 删除此标题
  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;}

    });



欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5172716.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-11-18
下一篇 2022-11-18

发表评论

登录后才能评论

评论列表(0条)

保存