简体   繁体   English

在Javascript中,如何使用fetch()从一个API请求中读取多个流块?

[英]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.

相关问题 如何使用 fetch API 在 javascript 中下载具有多个块的单个文件 - How to download single file with multiple chunks in javascript using fetch API Javascript:如何从API提取特定数据? - Javascript: How do I fetch specific data from an API? 如何使用 reactjs 从多个 API 获取搜索结果 - How do I fetch search results from multiple API using reactjs 如何在每个请求仅支持一个 ID 的 API 端点中获取多个 ID? - How do I fetch more than one ID in an API endpoint that only supports one ID per request? 如何使用Javascript从JSON获取属性/值? - How do I fetch the attributes/values from JSON using Javascript? 如何使用 javascript 从 firebase 中的键中获取值 - How do I fetch the value from a key in firebase using javascript 如何使用javascript从REST API发送请求并接收响应? - How do I send request and recieve response from REST API using javascript? 如何使用来自网络套接字的网络音频 API 流式传输音频块? - how to stream audio chunks using web audio API coming from web-socket? 如何限制来自 fetch API 的流以节省带宽? - How can I limit the stream from fetch API to save bandwidth? 如何将我从 JavaScript 中的提取请求中获得的数据保存到我的 function 外部的变量中 - How do I save the data I get from a fetch request in JavaScript into a variable that is external to my function
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM