XMLHttpRequest分块响应,仅读取进行中的最后一个响应 [英] XMLHttpRequest chunked response, only read last response in progress

查看:65
本文介绍了XMLHttpRequest分块响应,仅读取进行中的最后一个响应的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将来自NodeJS应用程序的分块数据发送回浏览器.这些块实际上是json字符串.我遇到的问题是,每次调用 onprogress 函数时,它都会添加一串完整的数据.意味着将第二个响应块附加到第一个响应块上,依此类推.我只想获得立即"收到的数据块.

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.

代码如下:

    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("...").标头的设置也是如此:

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

推荐答案

这种基于索引的方法对我有用:

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

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

这篇关于XMLHttpRequest分块响应,仅读取进行中的最后一个响应的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆