recursal/MDN huggingface dataset:
Response: blob() method
=======================

 The **`blob()`** method of the `Response` interface takes
 a `Response` stream and reads it to completion. It returns a promise that
 resolves with a `Blob`.

Syntax
------


```js
blob()
```

### Parameters

None.

**Note:** If the `Response` has a
 `Response.type` of `"opaque"`, the resulting `Blob`
 will have a `Blob.size` of `0` and a `Blob.type` of
 empty string `""`, which renders it *useless* for methods like
 `URL.createObjectURL()`.


### Return value

A promise that resolves with a `Blob`.

Examples
--------

 In our fetch request example (run fetch request live), we
 create a new request using the `Request()` constructor,
 then use it to fetch a JPG. When the fetch is successful, we read a `Blob`
 out of the response using `blob()`, put it into an object URL using
 `URL.createObjectURL()`, and then set that URL as the source of an
 `<img>` element to display the image.


```js
const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => response.blob())
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
```

Specifications
--------------

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-blob① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: bodyUsed property
===========================

The **`bodyUsed`** read-only property of the `Response` interface is a boolean value that indicates whether the body has been read yet.

Value
-----

A boolean value.

Examples
--------

### Checking `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


```html
<button id="use">Use response</button>
<button id="reset">Reset</button>
<br />
<img id="my-image" src="" />
<pre id="log"></pre>
```


#### JavaScript


```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();
});
```


#### Result

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.

Specifications
--------------

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-bodyused① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: body property
=======================

The **`body`** read-only property of the `Response` interface is a `ReadableStream` of the body contents.

Value
-----

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.

The stream is a readable byte stream, which supports zero-copy reading using a `ReadableStreamBYOBReader`.

**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).

Examples
--------

### Copying an image

 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.


```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));
```

### Creating a BYOB reader

In this example we construct a `ReadableStreamBYOBReader` from the body using `ReadableStream.getReader({mode: 'byob'})`. We can then use this reader to implement zero copy transfer of the response data.


```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",
);
```

Specifications
--------------

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

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Fetch API
* Streams API
* ServiceWorker API
Response: redirect() static method
==================================

The **`redirect()`** static method of the `Response` interface returns a `Response` resulting in a redirect to the specified URL.

**Note:** This can be used alongside the ServiceWorker API.
 A controlling service worker could intercept a page's request and redirect it as desired.
 This will actually lead to a real redirect if a service worker sends it upstream.


Syntax
------


```js
Response.redirect(url)
Response.redirect(url, status)
```

### Parameters

`url`

The URL that the new response is to originate from.

`status` Optional

An optional number indicating the status code for the response: one of `301`, `302`, `303`, `307`, or `308`. If omitted, `302 (Found)` is used by default.

### Return value

A `Response` object.

### Exceptions

`RangeError`

The specified status is not a redirect status.

`TypeError`

The specified URL is invalid.

Examples
--------


```js
Response.redirect("https://www.example.com", 302);
```

Specifications
--------------

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-redirect① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: url property
======================

 The **`url`** read-only property of the `Response` interface contains the URL of the response.
 The value of the `url` property will be the final URL obtained after any redirects.

Value
-----

A string.

Examples
--------

 In our Fetch Response example (see Fetch Response live) we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`, extract a blob from the response using `Response.blob`, create an object URL out of it using `URL.createObjectURL()`, and display this in an `<img>`.

Note that at the top of the `fetch()` block we log the response `URL` to the console.


```js
const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => {
    console.log("response.url =", response.url); // response.url = https://mdn.github.io/dom-examples/fetch/fetch-response/flowers.jpg
    return response.blob();
  })
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
```

Specifications
--------------

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-url① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: json() method
=======================

 The **`json()`** method of the `Response` interface takes
 a `Response` stream and reads it to completion. It returns a promise which
 resolves with the result of parsing the body text as `JSON`.

Note that despite the method being named `json()`, the result is not JSON but is instead the result of taking JSON as input and parsing it to produce a JavaScript object.

Syntax
------


```js
json()
```

### Parameters

None.

### Return value

 A `Promise` that resolves to a JavaScript object. This object could be
 anything that can be represented by JSON — an object, an array, a string, a number…

Examples
--------

 In our fetch JSON example (run fetch JSON live), we create a new request using the `Request()` constructor, then use it to fetch a `.json` file. When the
 fetch is successful, we read and parse the data using `json()`, then read
 values out of the resulting objects as you'd expect and insert them into list items to
 display our product data.


```js
const myList = document.querySelector("ul");
const myRequest = new Request("products.json");

fetch(myRequest)
  .then((response) => response.json())
  .then((data) => {
    for (const product of data.products) {
      const listItem = document.createElement("li");
      listItem.appendChild(document.createElement("strong")).textContent =
        product.Name;
      listItem.append(` can be found in ${product.Location}. Cost: `);
      listItem.appendChild(document.createElement("strong")).textContent =
        `£${product.Price}`;
      myList.appendChild(listItem);
    }
  })
  .catch(console.error);
```

Specifications
--------------

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-json① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ServiceWorker API
* Cross-Origin Resource Sharing (CORS)
* HTTP
Response: type property
=======================

 The **`type`** read-only property of the `Response` interface contains the type of the response.
 It can be one of the following:

* `basic`: Normal, same origin response, with all headers exposed except "Set-Cookie".
* `cors`: Response was received from a valid cross-origin request. Certain headers and the body may be accessed.
* `error`: Network error.
 No useful information describing the error is available.
 The Response's status is 0, headers are empty and immutable.
 This is the type for a Response obtained from `Response.error()`.
* `opaque`: Response for "no-cors" request to cross-origin resource.
 Severely restricted.
* `opaqueredirect`: The fetch request was made with `redirect: "manual"`.
 The Response's status is 0, headers are empty, body is null and trailer is empty.

**Note:** An "error" Response never really gets exposed to script: such a response to a `fetch()` would reject the promise.

Value
-----

A `ResponseType` string indicating the type of the response.

Examples
--------

 In our Fetch Response example (see Fetch Response live) we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`, extract a blob from the response using `Response.blob`, create an object URL out of it using `URL.createObjectURL()`, and display this in an `<img>`.

Note that at the top of the `fetch()` block we log the response `type` to the console.


```js
const myImage = document.querySelector("img");

const myRequest = new Request("flowers.jpg");

fetch(myRequest)
  .then((response) => {
    console.log("response.type =", response.type); // response.type = 'basic'
    return response.blob();
  })
  .then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    myImage.src = objectURL;
  });
```

Specifications
--------------

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-type① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: redirected property
=============================

The read-only **`redirected`** property of the `Response` interface indicates whether or not the response is the result of a request you made which was redirected.

**Note:** Relying on redirected to filter out redirects makes it easy for a forged redirect to prevent your content from working as expected.
 Instead, you should do the filtering when you call `fetch()`.
 See the example Disallowing redirects, which shows this being done.


Value
-----

A boolean value which is `true` if the response indicates that your request was redirected.

Examples
--------

### Detecting redirects

 Checking to see if the response comes from a redirected request is as simple as checking this flag on the `Response` object.
 In the code below, a textual message is inserted into an element when a redirect occurred during the fetch operation.
 Note, however, that this isn't as safe as outright rejecting redirects if they're unexpected, as described under Disallowing redirects below.

The `url` property returns the final URL after redirects.


```js
fetch("awesome-picture.jpg")
  .then((response) => {
    const elem = document.getElementById("warning-message-box");
    elem.textContent = response.redirected ? "Unexpected redirect" : "";
    // final url obtained after redirects
    console.log(response.url);
    return response.blob();
  })
  .then((imageBlob) => {
    const imgObjectURL = URL.createObjectURL(imageBlob);
    document.getElementById("img-element-id").src = imgObjectURL;
  });
```

### Disallowing redirects

Because using redirected to manually filter out redirects can allow forgery of redirects, you should instead set the redirect mode to `"error"` in the `init` parameter when calling `fetch()`, like this:


```js
fetch("awesome-picture.jpg", { redirect: "error" })
  .then((response) => response.blob())
  .then((imageBlob) => {
    const imgObjectURL = URL.createObjectURL(imageBlob);
    document.getElementById("img-element-id").src = imgObjectURL;
  });
```

Specifications
--------------

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-redirected① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Fetch API
* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: formData() method
===========================

 The **`formData()`** method of the `Response` interface
 takes a `Response` stream and reads it to completion. It returns a promise
 that resolves with a `FormData` object.


**Note:** This is mainly relevant to service workers. If a user submits
 a form and a service worker intercepts the request, you could for example call
 `formData()` on it to obtain a key-value map, modify some fields, then send
 the form onwards to the server (or use it locally).


Syntax
------


```js
formData()
```

### Parameters

None.

### Return value

A `Promise` that resolves with a `FormData` object.

Examples
--------

TBD.

Specifications
--------------

| Specification |
| --- |
| Fetch Standard # ref-for-dom-body-formdata① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
Response: clone() method
========================

The **`clone()`** method of the `Response` interface creates a clone of a response object, identical in every way, but stored in a different variable.

 Like the underlying `ReadableStream.tee` api,
 the `body` of a cloned `Response`
 will signal backpressure at the rate of the *faster* consumer of the two bodies,
 and unread data is enqueued internally on the slower consumed `body`
 without any limit or backpressure.
 Backpressure refers to the mechanism by which the streaming consumer of data
 (in this case, the code that reads the body)
 slows down the producer of data (such as the TCP server)
 so as not to load large amounts of data in memory
 that is waiting to be used by the application.
 If only one cloned branch is consumed, then the entire body will be buffered in memory.
 Therefore, `clone()` is one way to read a response twice in sequence,
 but you should not use it to read very large bodies
 in parallel at different speeds.

`clone()` throws a `TypeError` if the response body has already been used.
 In fact, the main reason `clone()` exists is to allow multiple uses of body objects (when they are one-use only.)

Syntax
------


```js
clone()
```

### Parameters

None.

### Return value

A `Response` object.

Examples
--------

 In our Fetch Response clone example (see Fetch Response clone live) we create a new `Request` object using the `Request()` constructor, passing it a JPG path.
 We then fetch this request using `fetch()`.
 When the fetch resolves successfully, we clone it, extract a blob from both responses using two `Response.blob` calls, create object URLs out of the blobs using
 `URL.createObjectURL()`, and display them in two separate `<img>` elements.


```js
const image1 = document.querySelector(".img1");
const image2 = document.querySelector(".img2");

const myRequest = new Request("flowers.jpg");

fetch(myRequest).then((response) => {
  const response2 = response.clone();

  response.blob().then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    image1.src = objectURL;
  });

  response2.blob().then((myBlob) => {
    const objectURL = URL.createObjectURL(myBlob);
    image2.src = objectURL;
  });
});
```

Specifications
--------------

| Specification |
| --- |
| Fetch Standard # ref-for-dom-response-clone① |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* ServiceWorker API
* HTTP access control (CORS)
* HTTP
WebTransportDatagramDuplexStream: outgoingMaxAge property
=========================================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`outgoingMaxAge`** property of the `WebTransportDatagramDuplexStream` interface gets or sets the maximum age for outgoing datagrams, in milliseconds.

**Note:** This feature is available in Web Workers

Value
-----

A number, or `null` if no maximum age has been set.

Examples
--------


```js
const url = "https://example.com:4999/wt";

async function initTransport(url) {
  // Initialize transport connection
  const transport = new WebTransport(url);

  // The connection can be used once ready fulfills
  await transport.ready;

  const datagrams = transport.datagrams;

  // set outgoingMaxAge
  datagrams.outgoingMaxAge = 2000;

  // get outgoingMaxAge
  console.log(datagrams.outgoingMaxAge);
}
```

Specifications
--------------

| Specification |
| --- |
| WebTransport # dom-webtransportdatagramduplexstream-outgoingmaxage |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using WebTransport
* WebSockets API
* Streams API
* WebTransport over HTTP/3
WebTransportDatagramDuplexStream: incomingMaxAge property
=========================================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`incomingMaxAge`** property of the `WebTransportDatagramDuplexStream` interface gets or sets the maximum age for incoming datagrams, in milliseconds.

**Note:** This feature is available in Web Workers

Value
-----

A number, or `null` if no maximum age has been set.

Examples
--------


```js
const url = "https://example.com:4999/wt";

async function initTransport(url) {
  // Initialize transport connection
  const transport = new WebTransport(url);

  // The connection can be used once ready fulfills
  await transport.ready;

  const datagrams = transport.datagrams;

  // set incomingMaxAge
  datagrams.incomingMaxAge = 2000;

  // get incomingMaxAge
  console.log(datagrams.incomingMaxAge);
}
```

Specifications
--------------

| Specification |
| --- |
| WebTransport # dom-webtransportdatagramduplexstream-incomingmaxage |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using WebTransport
* WebSockets API
* Streams API
* WebTransport over HTTP/3
WebTransportDatagramDuplexStream: outgoingHighWaterMark property
================================================================

Limited availability
--------------------

This feature is not Baseline because it does not work in some of the most widely-used browsers.

* Learn more
* See full compatibility
* Report feedback
The **`outgoingHighWaterMark`** property of the `WebTransportDatagramDuplexStream` interface gets or sets the high water mark for outgoing chunks of data — this is the maximum size, in chunks, that the outgoing `WritableStream`'s internal queue can reach before it is considered full. See Internal queues and queuing strategies for more information.

**Note:** This feature is available in Web Workers

Value
-----

A number.

Examples
--------


```js
const url = "https://example.com:4999/wt";

async function initTransport(url) {
  // Initialize transport connection
  const transport = new WebTransport(url);

  // The connection can be used once ready fulfills
  await transport.ready;

  const datagrams = transport.datagrams;

  // set outgoingHighWaterMark
  datagrams.outgoingHighWaterMark = 20000;

  // get outgoingHighWaterMark
  console.log(datagrams.outgoingHighWaterMark);
}
```

Specifications
--------------

| Specification |
| --- |
| WebTransport # dom-webtransportdatagramduplexstream-outgoinghighwatermark |

Browser compatibility
---------------------

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

See also
--------

* Using WebTransport
* WebSockets API
* Streams API
* WebTransport over HTTP/3