[英]In Javascript, how do I read multiple stream chunks from one API request using fetch()?
In my Node/Express backend, I have a long (10 - 15sec) API call that sets up a user's account. 在我的Node / Express后端,我有一个很长的(10 - 15秒)API调用来设置用户的帐户。
The call is triggered from my front-end by doing a simple fetch('my/api/url')
GET request. 通过执行简单的
fetch('my/api/url')
GET请求从我的前端触发调用。
I'd like to be able to send messages to the frontend/my user about the status of the request. 我希望能够向前端/我的用户发送有关请求状态的消息。 ("Setting up your profile", "Downloading your contacts", "Processing data" etc etc etc)
(“设置您的个人资料”,“下载您的联系人”,“处理数据”等等)
In my Express route, I'm (attempting) sending data via: 在我的Express路线中,我(尝试)通过以下方式发送数据:
exports.setupAccount = async () => {
res.write("Getting contacts");
// A bunch of code and async awaits
// and when it's done...
res.write(`Retrieved ${contacts.length} contacts!`);
}
I'm trying to comprehend the Mozilla Fetch() API at the moment and am not even sure if I'm looking in the right place. 我正在尝试理解Mozilla Fetch()API ,我甚至不确定我是否正在寻找合适的位置。
In my frontend (just vanilla JS for now) I'm doing: 在我的前端(现在只是香草JS)我正在做:
fetch('/my/setup/api')
.then(response => {
const reader = response.body.getReader();
reader.read().then(async ({ done, value }) => {
console.log("VALUE", value); // <== This returns a Uint8Array
var str = String.fromCharCode.apply(null, value);
console.log("Message from API:", str);
})
})
This works, but only gives me the first res.write()
sent from the server, and doesn't log out subsequent writes. 这
res.write()
,但只给我从服务器发送的第一个 res.write()
,并且不会注销后续写入。 How do I read multiple stream chunks using this fetch
/ getReader()
method? 如何使用此
fetch
/ getReader()
方法读取多个流块?
Found an answer that works with vanilla JS, using a while
loop with await
: 找到一个与vanilla JS一起使用的答案,使用
while
循环并await
:
fetch('/my/api')
.then(async response => {
const reader = response.body.getReader();
while(true) {
const {done, value} = await reader.read();
// If it's done, there will be no value
if (done) {
console.log("Done!");
break;
}
// value is Uint8Array of the chunk bytes
var str = String.fromCharCode.apply(null, value);
console.log(str)
}
})
Using response.text()
will read the stream to completion. 使用
response.text()
将读取流完成。 We can also use the Response
object to retrieve other formats like blobs ( response.blob()
) or json ( response.json()
) as well. 我们也可以使用
Response
对象来检索其他格式,如blob( response.blob()
)或json( response.json()
)。
fetch('/my/setup/api')
.then(response => response.text())
.then(text => console.log("Message from API:", text))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.