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①

浏览器兼容性

另见