流 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.