Response: body 屬性

Baseline 廣泛可用 *

此功能已成熟,並可在多種裝置和瀏覽器版本上使用。自 ⁨2019 年 1 月⁩起,它已在所有瀏覽器中可用。

* 此特性的某些部分可能存在不同級別的支援。

注意:此功能在 Web Workers 中可用。

Response 介面的只讀屬性 body 是一個包含響應正文內容的 ReadableStream

一個 ReadableStream,或者對於任何使用 null body 屬性 構造Response 物件,或者對於任何沒有 正文 的實際 HTTP 響應,則為 null

該流是一個 可讀位元組流,它支援使用 ReadableStreamBYOBReader 進行零複製讀取。

注意: 當前瀏覽器並不完全遵守規範要求,對於沒有正文的響應(例如,對 HEAD 請求的響應,或 204 No Content 響應)將 body 屬性設定為 null

示例

複製圖片

在我們 簡單的流泵 示例中,我們獲取了一個圖片,使用 response.body 暴露響應的流,使用 ReadableStream.getReader() 建立一個讀取器,然後將該流的塊排入第二個自定義的可讀流中——有效地建立了圖片的相同副本。

js
const image = document.getElementById("target");

// Fetch the original image
fetch("./tortoise.png")
  // Retrieve its body as ReadableStream
  .then((response) => response.body)
  .then((body) => {
    const reader = body.getReader();

    return new ReadableStream({
      start(controller) {
        return pump();

        function pump() {
          return reader.read().then(({ done, value }) => {
            // When no more data needs to be consumed, close the stream
            if (done) {
              controller.close();
              return;
            }

            // Enqueue the next data chunk into our target stream
            controller.enqueue(value);
            return pump();
          });
        }
      },
    });
  })
  .then((stream) => new Response(stream))
  .then((response) => response.blob())
  .then((blob) => URL.createObjectURL(blob))
  .then((url) => console.log((image.src = url)))
  .catch((err) => console.error(err));

建立 BYOB 讀取器

在此示例中,我們使用 ReadableStream.getReader({mode: 'byob'}) 從正文中構造一個 ReadableStreamBYOBReader。然後,我們可以使用此讀取器來實現響應資料的零複製傳輸。

js
async function getProducts(url) {
  const response = await fetch(url);
  const reader = response.body.getReader({ mode: "byob" });
  // read the response
}

getProducts(
  "https://mdn.github.io/learning-area/javascript/apis/fetching-data/can-store/products.json",
);

規範

規範
Fetch
# ref-for-dom-body-body①

瀏覽器相容性

另見