最近用koa2做请求转发时,采用了request(options).pipe(ctx.res)的方法,结果出现了有时候前端获得的数据是分片的。
后来翻阅文档,采取了如下方式解决:
const PassThrough = require('stream').PassThrough;
ctx.body = request(options)
.on('response', response => {
Object.keys(response.headers).forEach((key) => {
// if ('content-length' === key) return;
if ('transfer-encoding' === key) return;
ctx.set(key, response.headers[key]);
});
})
.on('error', ctx.onerror)
.pipe(PassThrough())
参考文档:
https://github.com/koajs/koa/pull/612
可是这样的解决方案我觉得并不好,header还要设置。
原生的stream.pipe(res)貌似就没有这样的问题。 继续寻求更好的解决方案