最近用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)貌似就没有这样的问题。 继续寻求更好的解决方案
本文探讨了使用Koa2进行请求转发时遇到的数据分片问题,并分享了一种解决方案,通过PassThrough流和手动设置响应头来避免前端接收到分片数据。同时,作者对现有方案表达了不满,寻求更优的处理方式。
2922

被折叠的 条评论
为什么被折叠?



