流 API - 响应体



在 Stream API 中,body 是 Response 接口的一个属性。它用于获取 ReadableStream 的主体内容。这是一个只读属性。响应体不是一次性发送,而是分小块发送,客户端在收到数据后立即开始处理,无需等待完整响应。

语法

Response.body

此属性对于任何使用 null body 属性创建的 Response 对象,返回 ReadableStream 或 null。

示例

在下面的程序中,我们将看到如何在 Stream API 中使用 Response Body。为此,我们使用 fetch() 向给定的 URL 发送 GET 请求。如果响应成功,则使用 response.body.getReader() 获取响应体作为“ReadableStream”。然后我们定义一个 readMyStream() 函数来读取从流中接收的数据块。如果发生任何错误,则 catch() 函数会成功处理。

<script>
   // fetch() function to send GET request 
   fetch('http://example.com/')
   .then(response => {
      if (response.ok) {
      // Using body property we get the ReadableStream 
      const myReader = response.body.getReader();
   
      // Using this function we read the chunks 
      function readMyStream() {
         return myReader.read().then(({ done, value }) => {
            if (done) {
               // Stream is completed
               return;
            }
            // Process the data from the chunks 
            const receivedData = new TextDecoder().decode(value);
            console.log(receivedData);
   
            // Continue reading 
            return readMyStream();
         });
      }
      return readMyStream();
      } 
   })
   .catch(error => {
      // Handling error
      console.log('Found Error:', error);
   });
</script>

结论

这就是 Response Body 的工作方式。在使用 Response body 之前,始终检查指定的 API 是否支持流式响应,因为并非所有 API 都支持流式响应。在下一篇文章中,我们将学习 Stream API 中的字节读取器。

广告
© . All rights reserved.