Nodejs res.end() [和其他版本的发送响应,如 res.write() 等] 不发送完整的字符串,介于两者



场景

我正在创建一个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内容。

我正在考虑不涉及写入和读取文件的解决方案。只需在收到响应时直接发送响应即可

操作目标服务器响应内容后,内容长度会更改,因此您必须重新计算内容长度并重写内容长度标头,或者只是删除内容长度标头,

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

相关内容

最新更新