The body
read-only property of the Response
interface is a ReadableStream
of the body contents.
The body
read-only property of the Response
interface is a ReadableStream
of the body contents.
A ReadableStream
, or else null
for any Response
object constructed with a null body
property, or for any actual HTTP response that has no body.
Note: Current browsers don't actually conform to the spec requirement to set the body
property to null
for responses with no body (for example, responses to HEAD
requests, or 204 No Content
responses).
In our simple stream pump example we fetch an image, expose the response's stream using response.body
, create a reader using ReadableStream.getReader()
, then enqueue that stream's chunks into a second, custom readable stream — effectively creating an identical copy of the image.
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));
Specification |
---|
Fetch Standard # ref-for-dom-body-body① |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
body |
43 |
14 |
65 |
No |
30 |
10.1 |
43 |
43 |
65 |
30 |
10.3 |
4.0 |
© 2005–2021 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Response/body