- AJAX 教程
- AJAX - 首頁
- AJAX - 什麼是 AJAX?
- AJAX - 歷史
- AJAX - 動態網站與靜態網站
- AJAX - 技術
- AJAX - 操作
- AJAX - XMLHttpRequest
- AJAX - 傳送請求
- AJAX - 請求型別
- AJAX - 處理響應
- AJAX - 處理二進位制資料
- AJAX - 提交表單
- AJAX - 檔案上傳
- AJAX - FormData 物件
- AJAX - 傳送 POST 請求
- AJAX - 傳送 PUT 請求
- AJAX - 傳送 JSON 資料
- AJAX - 傳送資料物件
- AJAX - 監控進度
- AJAX - 狀態碼
- AJAX - 應用
- AJAX - 瀏覽器相容性
- AJAX - 示例
- AJAX - 瀏覽器支援
- AJAX - XMLHttpRequest
- AJAX - 資料庫操作
- AJAX - 安全性
- AJAX - 問題
- Fetch API 基礎
- Fetch API - 基礎
- Fetch API 與 XMLHttpRequest 的比較
- Fetch API - 瀏覽器相容性
- Fetch API - 頭部資訊
- Fetch API - 請求
- Fetch API - 響應
- Fetch API - 體資料
- Fetch API - 憑據
- Fetch API - 傳送 GET 請求
- Fetch API - 傳送 POST 請求
- Fetch API - 傳送 PUT 請求
- Fetch API - 傳送 JSON 資料
- Fetch API - 傳送資料物件
- Fetch API - 自定義請求物件
- Fetch API - 上傳檔案
- Fetch API - 處理二進位制資料
- Fetch API - 狀態碼
- Stream API 基礎
- Stream API - 基礎
- Stream API - 可讀流
- Stream API - 可寫流
- Stream API - 變換流
- Stream API - 請求物件
- 流 API - 響應體
- Stream API - 錯誤處理
- AJAX 有用資源
- AJAX - 快速指南
- AJAX - 有用資源
- AJAX - 討論
流 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 中的位元組讀取器。
廣告