The bodyUsed
read-only property of the Response
interface is a boolean value that indicates whether the body has been read yet.
The bodyUsed
read-only property of the Response
interface is a boolean value that indicates whether the body has been read yet.
A boolean value.
bodyUsed
This example illustrates that reading the body of a response changes the value of bodyUsed
from false
to true
.
The example contains an empty image.
When the example's JavaScript runs, we fetch an image and assigns the returned promise to a variable responsePromise
.
When the user clicks "Use response", we check whether the response has been used already. If it has, we print a message. If it has not, we read the response body and used it to provide a value for the image's src
attribute.
html
<button id="use">Use response</button> <button id="reset">Reset</button> <br /> <img id="my-image" src="" /> <pre id="log"></pre>
js
const useResponse = document.querySelector("#use"); const reset = document.querySelector("#reset"); const myImage = document.querySelector("#my-image"); const log = document.querySelector("#log"); const responsePromise = fetch( "https://upload.wikimedia.org/wikipedia/commons/7/77/Delete_key1.jpg", ); useResponse.addEventListener("click", async () => { const response = await responsePromise; if (response.bodyUsed) { log.textContent = "Body has already been used!"; } else { const result = await response.blob(); const objectURL = URL.createObjectURL(result); myImage.src = objectURL; } }); reset.addEventListener("click", () => { document.location.reload(); });
Initially there is no value for the image. If you click "Use response" once, then bodyUsed
is false
, so we read the response and set the image. If you then click "Use response" again, then bodyUsed
is true
, and we print the message.
Click "Reset" to reload the example, so you can try again.
Specification |
---|
Fetch Standard # ref-for-dom-body-bodyused① |
Desktop | Mobile | |||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|
Chrome | Edge | Firefox | Internet Explorer | Opera | Safari | WebView Android | Chrome Android | Firefox for Android | Opera Android | Safari on IOS | Samsung Internet | |
bodyUsed |
42 | 14 | 39 | No | 29 | 10.1 | 42 | 42 | 39 | 29 | 10.3 | 4.0 |
© 2005–2023 MDN contributors.
Licensed under the Creative Commons Attribution-ShareAlike License v2.5 or later.
https://developer.mozilla.org/en-US/docs/Web/API/Response/bodyUsed