Response: body プロパティ

Baseline Widely available *

This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.

* Some parts of this feature may have varying levels of support.

bodyResponse インターフェイスの読み取り専用プロパティで、本体コンテンツの ReadableStream です。

ReadableStream、または Response オブジェクトが構築時に body プロパティが null であった場合、あるいは HTTP レスポンス本体がなかった場合には null になります。

ストリームは読み取り可能なバイトストリームで、 ReadableStreamBYOBReader を用いたゼロコピー移譲に対応しています。

メモ: 現在のブラウザーは、本体なしのレスポンス(例えば、 HEAD リクエストに対するレスポンスや、 204 No Content レスポンス)には body プロパティを null に設定するという仕様に実際には適合していません。

画像の複製

単純なストリームポンプの例では、画像を読み取り、 response.body を使用してレスポンスのストリームを公開し、ReadableStream.getReader() を使用してリーダーを作成し、そのストリームのチャンクを 2 番目のカスタム読み取り可能なストリームのキューに入れます。画像の同一コピーを効果的に作成します。

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

// 元の画像をフェッチ
fetch("./tortoise.png")
  // その body を 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 }) => {
            // データを消費する必要がなくなったら、ストリームを閉じます
            if (done) {
              controller.close();
              return;
            }

            // 次のデータチャンクを対象のストリームのキューに入れます
            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 リーダーの作成

この例では、 ReadableStreamBYOBReader を使用して本体から ReadableStream.getReader({mode: 'byob'}) を構築します。このリーダーを使用して、レスポンスデータのゼロコピー移譲を実装することができます。

js
async function getProducts(url) {
  const response = await fetch(url);
  const reader = response.body.getReader({ mode: "byob" });
  // このレスポンスを読む
}

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

仕様書

Specification
Fetch
# ref-for-dom-body-body①

ブラウザーの互換性

Report problems with this compatibility data on GitHub
desktopmobileserver
Chrome
Edge
Firefox
Opera
Safari
Chrome Android
Firefox for Android
Opera Android
Safari on iOS
Samsung Internet
WebView Android
WebView on iOS
Deno
Node.js
body
body is a readable byte stream

Legend

Tip: you can click/tap on a cell for more information.

Full support
Full support
No support
No support

関連情報