Nodejs res.end() [以及发送响应的其他版本,如 res.write() 等] 不发送完整的字符串,在两者之间中断

Nodejs res.end() [and other versions of sending response like res.write() etc] not sending complete string, breaking in between

场景

我正在创建一个 nodejs 服务器,它将充当实际客户端和实际服务器之间的中间服务器。即我通过我的 nodejs 服务器向网站发送请求,从实际(网站)服务器接收响应,并将其转发给客户端(浏览器)。

这是执行此操作的部分代码

const cheerio   = require('cheerio');

//#================================================================
// include other files and declare variables
//#================================================================

app.get('/*', (req, res) => {

    //#================================================================
    // some code...
    //#================================================================

    request(options, function(error, response, body){
        if (!error && response.statusCode == 200) {
            res.writeHead(200, headers);

            if (String(response.headers['content-type']).indexOf('text/html') !== -1){
                var $ = cheerio.load(body);

                //#================================================
                // perform html manipulations
                //#================================================

                //send the html content as response
                res.end($.html());

            }else{
                res.end(body);
            }

        }else{
            res.send({status: 500, error: error});
        }
    });
}

一切正常,直到我偶然发现这个特定的网站 https://www.voonik.com/recommendations/bright-cotton-a-line-kurta-for-women-blue-printed-bcown-007b-38-1f2073ca

如果你看一下它的视图源,它或多或少是这样的

<!doctype html>
<html lang="en-in" data-reactid=".mc12nbyapk" data-react-checksum="-2121099716">
<!-- rest of the html code -->
...
<script type="text/javascript" charset="UTF-8" data-reactid=".mc12nbyapk.1.1">
window.NREUM||(NREUM={});NREUM.info = {"agent":"","beacon":"bam.nr-data.net","errorBeacon":"bam.nr-data.net"...
...
</script></body></html>

当我在我的响应对象中发送这个非常 html 时,它发送不完整 html 即在最后一个脚本标记的某处中断。

我也安慰记录了 html,它打印了整个字符串。但是发送相同的响应对象发送一半。

也试过res.write(); res.send() 并将 html 内容存储在一个变量中,然后发送该变量,但结果是相同的,即不完整的 html 内容。

我正在考虑不涉及写入和读取文件的解决方案。收到回复后直接发送即可

你操作目标服务器响应内容后,content长度发生变化,必须重新计算content长度并重写content-length header,或者直接删除content-length header,

将此代码 delete headers['content-length'] 放在 res.writeHead(200, headers); 此行之前。