koa2做請求轉發


最近用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://koa.bootcss.com/

https://github.com/koajs/koa/pull/612 

 

可是這樣的解決方案我覺得並不好,header還要設置。

原生的stream.pipe(res)貌似就沒有這樣的問題。 繼續尋求更好的解決方案

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM