我正在将分块数据从 NodeJS 应用程序发送回浏览器。这些块实际上是 json 字符串。我遇到的问题是每次onprogress
调用函数时,它会添加完整数据的字符串。这意味着第二个响应块将附加到第一个响应块,依此类推。我只想获取“刚刚”收到的块。
这是代码:
console.log("Start scan...");
var xhr = new XMLHttpRequest();
xhr.responseType = "text";
xhr.open("GET", "/servers/scan", true);
xhr.onprogress = function () {
console.log("PROGRESS:", xhr.responseText);
}
xhr.send();
实际上,当第三个响应到来时,xhr.responseText 的内容还包含第一个和第二个响应的响应文本。我检查了服务器发送的内容,看起来没有问题。将 Node 与 Express 结合使用,并使用res.send("...")
一些时间。标题也设置如下:
res.setHeader('Transfer-Encoding', 'chunked');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.set('Content-Type', 'text/json');
这种基于索引的方法对我有用:
var last_index = 0;
var xhr = new XMLHttpRequest();
xhr.open("GET", "/servers/scan");
xhr.onprogress = function () {
var curr_index = xhr.responseText.length;
if (last_index == curr_index) return;
var s = xhr.responseText.substring(last_index, curr_index);
last_index = curr_index;
console.log("PROGRESS:", s);
};
xhr.send();
灵感来自https://friendbit.com/js/partial-xmlhttprequest-responses/
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)