XMLHttpRequest chunked response,只读取最后的响应。

时间:2022-09-18 17:09:21

I'm sending chunked data from a NodeJS application back to the browser. The chunks are really json strings. Problem I'm having is that every time the onprogress function is called, it adds on a string of the complete data. Meaning that response chunk number two, is appended to response chunk number one, and so on. I'd like to get ONLY the "just now" received chunk.

我将NodeJS应用程序中的数据块发送回浏览器。这些块实际上是json字符串。问题是,每次调用onprogress函数时,它都会添加一个完整数据的字符串。表示响应块2,被附加到响应块1,以此类推。我只希望得到“刚才”收到的部分。

Here's the code:

这是代码:

    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();

So really, the contents of xhr.responseText contains, when the third response comes, also the response text for the first and the second response. I've checked what the server is sending, and it doesn't look like there's a problem there. Using Node with Express, and sending with res.send("...") a couple of times. Also headers are set like so:

xhr的内容。responseText包含当第三个响应出现时,第一个和第二个响应的响应文本。我检查了服务器正在发送什么,看起来没有问题。使用带有Express的节点,并使用res.send(“…”)发送几次。标题也设置为:

res.setHeader('Transfer-Encoding', 'chunked');
res.setHeader('X-Content-Type-Options', 'nosniff');
res.set('Content-Type', 'text/json');

1 个解决方案

#1


3  

This index based approach works for me:

这种基于指数的方法对我很有效:

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();

Inspired by https://friendlybit.com/js/partial-xmlhttprequest-responses/

灵感来自于https://friendlybit.com/js/partial-xmlhttprequest-responses/

#1


3  

This index based approach works for me:

这种基于指数的方法对我很有效:

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();

Inspired by https://friendlybit.com/js/partial-xmlhttprequest-responses/

灵感来自于https://friendlybit.com/js/partial-xmlhttprequest-responses/