Response: thuộc tính body

Baseline Widely available *

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

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

Note: This feature is available in Web Workers.

Thuộc tính chỉ đọc body của giao diện Response là một ReadableStream của nội dung thân phản hồi.

Giá trị

Một ReadableStream, hoặc null đối với bất kỳ đối tượng Response nào được khởi tạo với thuộc tính body là null, hoặc đối với bất kỳ phản hồi HTTP thực tế nào không có body.

Luồng này là một readable byte stream, hỗ trợ đọc zero-copy bằng ReadableStreamBYOBReader.

Note: Các trình duyệt hiện tại thực tế chưa tuân thủ yêu cầu của spec là đặt thuộc tính body thành null đối với phản hồi không có body, chẳng hạn phản hồi cho yêu cầu HEAD hoặc phản hồi 204 No Content.

Ví dụ

Sao chép một hình ảnh

Trong ví dụ simple stream pump của chúng tôi, chúng ta fetch một hình ảnh, truy cập luồng của phản hồi qua response.body, tạo một reader bằng ReadableStream.getReader(), rồi đẩy các chunk của luồng đó vào một readable stream tùy chỉnh thứ hai, qua đó tạo ra một bản sao tương tự của hình ảnh.

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

// Fetch hình ảnh gốc
fetch("./tortoise.png")
  // Lấy body dưới dạng 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 }) => {
            // Khi không còn dữ liệu cần đọc, đóng stream
            if (done) {
              controller.close();
              return;
            }

            // Đưa chunk dữ liệu tiếp theo vào stream đích của chúng ta
            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));

Tạo BYOB reader

Trong ví dụ này, chúng ta tạo một ReadableStreamBYOBReader từ body bằng ReadableStream.getReader({mode: 'byob'}). Sau đó có thể dùng reader này để thực hiện truyền dữ liệu phản hồi theo kiểu zero-copy.

js
async function getProducts(url) {
  const response = await fetch(url);
  const reader = response.body.getReader({ mode: "byob" });
  // đọc phản hồi
}

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

Thông số kỹ thuật

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

Tương thích trình duyệt

Xem thêm