Dan*_*éus 5 javascript xmlhttprequest chunked node.js
我正在将来自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();
Run Code Online (Sandbox Code Playgroud)
因此,实际上,xhr.responseText的内容在第三个响应到来时还包含第一个和第二个响应的响应文本。我检查了服务器正在发送的内容,看来那里没有问题。将Node与Express结合使用,并发送res.send("...")几次。标头也设置如下:
res.setHeader('Transfer-Encoding', 'chunked');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.set('Content-Type', 'text/json');
Run Code Online (Sandbox Code Playgroud)
这种基于索引的方法对我有用:
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();
Run Code Online (Sandbox Code Playgroud)
受到https://friendlybit.com/js/partial-xmlhttprequest-responses/的启发
| 归档时间: |
|
| 查看次数: |
4063 次 |
| 最近记录: |