最近用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)貌似就沒有這樣的問題。 繼續尋求更好的解決方案
