XMLHttpRequest chunked response, only read last response in progress

只愿长相守 提交于 2020-05-14 18:26:48

问题


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.

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:

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

回答1:


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://stackoverflow.com/questions/33635919/xmlhttprequest-chunked-response-only-read-last-response-in-progress

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!