### Header parsing example A: text/html; and A: x/x
Source: https://fetch.spec.whatwg.org/
Example of parsing multiple lines for the same header.
```text
A: text/html;"
A: x/x
```
--------------------------------
### Header parsing example A: x / x, A: , A: 1
Source: https://fetch.spec.whatwg.org/
Example of parsing multiple header lines with empty values.
```text
A: x / x
A: ,
A: 1
```
--------------------------------
### Header parsing example A: text/html;
Source: https://fetch.spec.whatwg.org/
Example of parsing a header with a semicolon.
```text
A: text/html;", x/x
```
--------------------------------
### Header parsing example A: x / x,,,1
Source: https://fetch.spec.whatwg.org/
Example of parsing headers with multiple commas.
```text
A: x / x,,,1
```
--------------------------------
### Access-Control-Expose-Headers configuration
Source: https://fetch.spec.whatwg.org/
Example response headers showing how to expose specific headers to the client.
```http
Content-Security-Policy: default-src 'self'
Strict-Transport-Security: max-age=31536000; includeSubdomains; preload
Access-Control-Expose-Headers: Content-Security-Policy
```
--------------------------------
### Header parsing example A: nosniff, B: sniff
Source: https://fetch.spec.whatwg.org/
Example of parsing multiple headers.
```text
A: nosniff
B: sniff
A:
```
--------------------------------
### Header parsing example A: nosniff
Source: https://fetch.spec.whatwg.org/
Example of parsing a single header value.
```text
A: nosniff,
```
--------------------------------
### Queue a deferred fetch with activation observation
Source: https://fetch.spec.whatwg.org/
This example queues a request to be fetched after 5 seconds and uses the returned FetchLaterResult to observe if the request was activated.
```javascript
const result = fetchLater("https://report.example.com", {
method: "POST",
body: JSON.stringify(myReport),
headers: { "Content-Type": "application/json" },
activateAfter: 5000
});
function check_if_fetched() {
return result.activated;
}
```
--------------------------------
### Queue a deferred fetch request
Source: https://fetch.spec.whatwg.org/
This example demonstrates how to queue a POST request to be fetched when the document is terminated.
```javascript
fetchLater("https://report.example.com", {
method: "POST",
body: JSON.stringify(myReport),
headers: { "Content-Type": "application/json" }
})
```
--------------------------------
### Header parsing example A: x/x;test="hi",y/y
Source: https://fetch.spec.whatwg.org/
Example of parsing a header with quoted strings.
```text
A: x/x;test="hi",y/y
```
--------------------------------
### Header parsing example B: sniff
Source: https://fetch.spec.whatwg.org/
Example of parsing a header list where the target header is missing.
```text
B: sniff
```
--------------------------------
### Header parsing example A: "1,2", 3
Source: https://fetch.spec.whatwg.org/
Example of parsing quoted values containing commas.
```text
A: "1,2", 3
```
--------------------------------
### Use FetchLaterResult with AbortSignal
Source: https://fetch.spec.whatwg.org/
This example shows how to use an AbortSignal to manage deferred requests, allowing for the abortion of previous requests when new events are accumulated.
```javascript
let accumulated_events = [];
let previous_result = null;
const abort_signal = new AbortSignal();
function accumulate_event(event) {
if (previous_result) {
if (previous_result.activated) {
// The request is already activated, we can start from scratch.
accumulated_events = [];
} else {
// Abort this request, and start a new one with all the events.
signal.abort();
}
}
accumulated_events.push(event);
result = fetchLater("https://report.example.com", {
method: "POST",
body: JSON.stringify(accumulated_events),
headers: { "Content-Type": "application/json" },
activateAfter: 5000,
abort_signal
});
}
```
--------------------------------
### Header parsing example A: "1,2", D: 4, A: 3
Source: https://fetch.spec.whatwg.org/
Example of parsing headers with interleaved values and quotes.
```text
A: "1,2"
D: 4
A: 3
```
--------------------------------
### Header parsing example A: x/x;test="hi", C: bingo, A: y/y
Source: https://fetch.spec.whatwg.org/
Example of parsing headers with interleaved values.
```text
A: x/x;test="hi"
C: **bingo**
A: y/y
```
--------------------------------
### Examples of fetchLater calls that throw errors
Source: https://fetch.spec.whatwg.org/
These examples demonstrate scenarios where fetchLater will throw an error, such as using untrusted URLs, dynamic streams, or detached windows.
```javascript
// Only potentially trustworthy URLs are supported.
fetchLater("http://untrusted.example.com");
// The length of the deferred request has to be known when.
fetchLater("https://origin.example.com", {body: someDynamicStream});
// Deferred fetching only works on active windows.
const detachedWindow = iframe.contentWindow;
iframe.remove();
detachedWindow.fetchLater("https://origin.example.com");
```
--------------------------------
### Ignore response body
Source: https://fetch.spec.whatwg.org/
Example of fetching a request without expecting a response, useful for fire-and-forget operations.
```text
Fetch a request whose URL is https://fire-and-forget.example.com/, method is POST, and client is this’s relevant settings object.
```
--------------------------------
### Example of Content-Type CORS preflight vulnerability
Source: https://fetch.spec.whatwg.org/
This example demonstrates a request that would bypass CORS preflight if the MIME type extraction algorithm were too forgiving, potentially allowing a naïve server to misinterpret the request body.
```javascript
fetch("https://victim.example/naïve-endpoint", {
method: "POST",
headers: [
["Content-Type", "application/json"],
["Content-Type", "text/plain"]
],
credentials: "include",
body: JSON.stringify(exerciseForTheReader)
});
```
--------------------------------
### Examples of fetchLater() calls exceeding reporting origin quota
Source: https://fetch.spec.whatwg.org/
These calls to fetchLater() will throw an error because the request size exceeds the 64 kibibytes quota allocated to a reporting origin.
```javascript
fetchLater(a_72_kb_url);
fetchLater("https://origin.example.com", {headers: headers_exceeding_64kb});
fetchLater(a_32_kb_url, {headers: headers_exceeding_32kb});
fetchLater("https://origin.example.com", {method: "POST", body: body_exceeding_64_kb});
fetchLater(a_62_kb_url /* with a 3kb referrer */);
```
--------------------------------
### get(name)
Source: https://fetch.spec.whatwg.org/
Returns the value of the specified header. Throws a TypeError if the name is not a valid header name.
```APIDOC
## get(name)
### Description
Returns the value of the specified header. Throws a TypeError if the name is not a valid header name.
### Method
get
### Parameters
- **name** (string) - Required - The header name.
### Returns
- The value of the header, or null if not present.
### Exceptions
- Throws a TypeError if name is not a header name.
```
--------------------------------
### Headers class
Source: https://fetch.spec.whatwg.org/
The Headers class represents HTTP headers. It allows you to create, append, delete, get, set, and check headers, and it is iterable.
```APIDOC
## Headers class
### Description
The Headers class represents HTTP headers. It allows you to create, append, delete, get, set, and check headers, and it is iterable.
### Constructor
new Headers(optional HeadersInit init)
### Methods
#### append(name, value)
Appends a header to headers.
#### delete(name)
Removes a header from headers.
#### get(name)
Returns as a string the values of all headers whose name is name, separated by a comma and a space.
#### getSetCookie()
Returns a list of the values for all headers whose name is Set-Cookie.
#### has(name)
Returns whether there is a header whose name is name.
#### set(name, value)
Replaces the value of the first header whose name is name with value and removes any remaining headers whose name is name.
### Iteration
for(const [name, value] of headers) - headers can be iterated over.
### Example
const meta = { "Content-Type": "text/xml", "Breaking-Bad": "<3" };
new Headers(meta);
// The above is equivalent to
const meta2 = [
[ "Content-Type", "text/xml" ],
[ "Breaking-Bad", "<3" ]
];
new Headers(meta2);
```
--------------------------------
### Fetch a resource as a Blob
Source: https://fetch.spec.whatwg.org/
Demonstrates fetching a file and processing it as a Blob.
```javascript
fetch("/music/pk/altes-kamuffel.flac")
.then(res => res.blob()).then(playBlob)
```
--------------------------------
### fetch(input, init)
Source: https://fetch.spec.whatwg.org/
Initiates a fetch request and returns a Promise that resolves to a Response object.
```APIDOC
## fetch(input, init)
### Description
Initiates a fetch request and returns a Promise that resolves to a Response object.
### Method
fetch
### Parameters
- **input** (RequestInfo) - Required - A Request object or a URL string.
- **init** (RequestInit) - Optional - An object containing request options.
### Request Example
```js
const response = await fetch("https://example.com", {method: "GET"});
```
### Response
#### Success Response
- **response** (Promise) - A Promise that resolves to a Response object.
```
--------------------------------
### Initialize Headers object
Source: https://fetch.spec.whatwg.org/
Shows equivalent ways to initialize a Headers object using an object or an array of arrays.
```javascript
const meta = { "Content-Type": "text/xml", "Breaking-Bad": "<3" };
new Headers(meta);
// The above is equivalent to
const meta2 = [
[ "Content-Type", "text/xml" ],
[ "Breaking-Bad", "<3" ]
];
new Headers(meta2);
```
--------------------------------
### fetch(input, init)
Source: https://fetch.spec.whatwg.org/
Method that initiates a fetch request and returns a Promise that resolves to a Response object. It accepts a RequestInfo input and optional RequestInit options.
```APIDOC
## fetch(input, init)
### Description
Method that initiates a fetch request and returns a Promise that resolves to a Response object. It accepts a RequestInfo input and optional RequestInit options.
### Method
METHOD
### Endpoint
fetch(input, init)
### Parameters
- **input** (RequestInfo) - Required - The resource to fetch.
- **init** (RequestInit) - Optional - Initialization options for the request.
### Response
Returns a Promise that resolves to a Response object.
```
--------------------------------
### fetchLater(input, init)
Source: https://fetch.spec.whatwg.org/
Schedules a fetch request to be sent later, returning a FetchLaterResult.
```APIDOC
## fetchLater(input, init)
### Description
Schedules a fetch request to be sent later, returning a FetchLaterResult.
### Method
fetchLater
### Parameters
- **input** (RequestInfo) - Required - A Request object or a URL string.
- **init** (DeferredRequestInit) - Optional - An object containing request options, including activateAfter.
### Request Example
```js
const result = fetchLater("https://example.com", {activateAfter: 1000});
```
### Response
#### Success Response
- **result** (FetchLaterResult) - An object with an `activated` boolean property.
```
--------------------------------
### fetchLater(input, init)
Source: https://fetch.spec.whatwg.org/
Method that schedules a fetch to be activated later. Returns a FetchLaterResult object with an activated attribute.
```APIDOC
## fetchLater(input, init)
### Description
Method that schedules a fetch to be activated later. Returns a FetchLaterResult object with an activated attribute.
### Method
METHOD
### Endpoint
fetchLater(input, init)
### Parameters
- **input** (RequestInfo) - Required - The resource to fetch.
- **init** (DeferredRequestInit) - Optional - Initialization options, including activateAfter.
### Response
Returns a FetchLaterResult object.
```
--------------------------------
### new Request(input, init)
Source: https://fetch.spec.whatwg.org/
Creates a new Request object. The input can be a string URL or another Request object. The init object allows setting various request properties.
```APIDOC
## new Request(input, init)
### Description
Creates a new Request object. The input can be a string URL or another Request object. The init object allows setting various request properties.
### Constructor
new Request(input, init)
### Parameters
- input (RequestInfo) - Required - A string URL or a Request object.
- init (RequestInit) - Optional - An object with properties to configure the request.
### RequestInit Properties
- method (ByteString) - Optional - A string to set the request's method.
- headers (HeadersInit) - Optional - A Headers object, object literal, or array of two-item arrays to set the request's headers.
- body (BodyInit) - Optional - A BodyInit object or null to set the request's body.
- referrer (USVString) - Optional - A string whose value is a same-origin URL, "about:client", or the empty string.
- referrerPolicy (ReferrerPolicy) - Optional - A referrer policy.
- mode (RequestMode) - Optional - A string indicating CORS mode. Defaults to "cors" if input is a string.
- credentials (RequestCredentials) - Optional - A string indicating credentials mode. Defaults to "same-origin" if input is a string.
- cache (RequestCache) - Optional - A string indicating cache mode.
- redirect (RequestRedirect) - Optional - A string indicating redirect mode.
- integrity (DOMString) - Optional - A string for integrity.
- keepalive (boolean) - Optional - A boolean for keepalive.
- signal (AbortSignal) - Optional - An AbortSignal object.
- duplex (RequestDuplex) - Optional - A string indicating duplex mode.
- priority (RequestPriority) - Optional - A string indicating priority.
- window (any) - Optional - Can only be set to null.
### Returns
A new Request object.
```
--------------------------------
### new Response(body, init)
Source: https://fetch.spec.whatwg.org/
Creates a new Response object with the given body and initialization options. The body can be null or a BodyInit, and init can specify status, statusText, and headers.
```APIDOC
## new Response(body, init)
### Description
Creates a new Response object with the given body and initialization options. The body can be null or a BodyInit, and init can specify status, statusText, and headers.
### Method
Constructor
### Parameters
#### Body
- **body** (BodyInit?) - Optional - The response body. If null, the response has no body.
#### Init (ResponseInit)
- **status** (unsigned short) - Optional - The HTTP status code. Default is 200. Must be in the range 200 to 599 inclusive.
- **statusText** (ByteString) - Optional - The status message. Default is empty string. Must match the reason-phrase token production if non-empty.
- **headers** (HeadersInit) - Optional - The response headers.
### Request Example
```javascript
const response = new Response('Hello', { status: 200, statusText: 'OK', headers: { 'Content-Type': 'text/plain' } });
```
### Response
Returns a new Response object.
```
--------------------------------
### new Headers(init)
Source: https://fetch.spec.whatwg.org/
Creates a new Headers object. If init is provided, it fills the headers with the given object or sequence.
```APIDOC
## new Headers(init)
### Description
Creates a new Headers object. If init is provided, it fills the headers with the given object or sequence.
### Constructor
`new Headers(init)`
### Parameters
- **init** (object or sequence) - Optional - An object or sequence of header pairs to initialize the headers.
### Behavior
- Sets the guard to "none".
- If init is given, fills the headers with init.
```
--------------------------------
### Fetch with URL query parameters
Source: https://fetch.spec.whatwg.org/
Constructs a URL with query parameters using URLSearchParams before fetching.
```javascript
var url = new URL("https://geo.example.org/api"),
params = {lat:35.696233, long:139.570431}
Object.keys(params).forEach(key => url.searchParams.append(key, params[key]))
fetch(url).then(/* … */)
```
--------------------------------
### Response.json(data, init)
Source: https://fetch.spec.whatwg.org/
Returns a new Response object with a JSON body.
```APIDOC
## Response.json(data, init)
### Description
Returns a new Response object with a JSON body.
### Method
json (static)
### Parameters
- **data** (any) - Required - The data to serialize as JSON.
- **init** (ResponseInit) - Optional - An object containing response options.
### Request Example
```js
const jsonResponse = Response.json({message: "Hello"});
```
### Response
#### Success Response
- **response** (Response) - A Response object with the JSON body.
```
--------------------------------
### fetchLater(input, init)
Source: https://fetch.spec.whatwg.org/
Queues a deferred fetch request. The request is fetched when the document is terminated or after the specified activateAfter delay. Returns a FetchLaterResult object.
```APIDOC
## fetchLater(input, init)
### Description
Queues a deferred fetch request. The request is fetched when the document is terminated or after the specified activateAfter delay. Returns a FetchLaterResult object.
### Method
fetchLater(input, init)
### Parameters
- **input** (Request or string) - Required - The request input, passed to the Request constructor.
- **init** (object) - Optional - An object with the following properties:
- **activateAfter** (number) - Optional - Delay in milliseconds before the request is activated. Must be non-negative.
- **method** (string) - Optional - HTTP method for the request.
- **body** (string or ReadableStream) - Optional - Request body. Must have a known length.
- **headers** (object) - Optional - Request headers.
- **abort_signal** (AbortSignal) - Optional - Signal to abort the deferred fetch.
### Return Value
Returns a new FetchLaterResult object with an activated getter.
### Exceptions
- **RangeError** - If activateAfter is less than 0.
- **TypeError** - If the document is not fully active, if the URL scheme is not HTTP(S), if the URL is not potentially trustworthy, or if the body length is unknown.
- **QuotaExceededError** - If the deferred-fetch quota is insufficient.
### Request Example
```
fetchLater("https://report.example.com", {
method: "POST",
body: JSON.stringify(myReport),
headers: { "Content-Type": "application/json" }
})
```
### Response
Returns a FetchLaterResult object.
### Response Example
```
const result = fetchLater("https://report.example.com", {
method: "POST",
body: JSON.stringify(myReport),
headers: { "Content-Type": "application/json" },
activateAfter: 5000
});
```
```
--------------------------------
### Request Interface and RequestInit Dictionary
Source: https://fetch.spec.whatwg.org/
Defines the Request interface, the RequestInit configuration dictionary, and associated enums for request modes, credentials, cache, and other properties.
```webidl
typedef (Request or USVString) RequestInfo;
[Exposed=(Window,Worker)]
interface Request {
constructor(RequestInfo input, optional RequestInit init = {});
readonly attribute ByteString method;
readonly attribute USVString url;
[SameObject] readonly attribute Headers headers;
readonly attribute RequestDestination destination;
readonly attribute USVString referrer;
readonly attribute ReferrerPolicy referrerPolicy;
readonly attribute RequestMode mode;
readonly attribute RequestCredentials credentials;
readonly attribute RequestCache cache;
readonly attribute RequestRedirect redirect;
readonly attribute DOMString integrity;
readonly attribute boolean keepalive;
readonly attribute boolean isReloadNavigation;
readonly attribute boolean isHistoryNavigation;
readonly attribute AbortSignal signal;
readonly attribute RequestDuplex duplex;
[NewObject] Request clone();
};
Request includes Body;
dictionary RequestInit {
ByteString method;
HeadersInit headers;
BodyInit? body;
USVString referrer;
ReferrerPolicy referrerPolicy;
RequestMode mode;
RequestCredentials credentials;
RequestCache cache;
RequestRedirect redirect;
DOMString integrity;
boolean keepalive;
AbortSignal? signal;
RequestDuplex duplex;
RequestPriority priority;
any window; // can only be set to null
};
enum RequestDestination { "", "audio", "audioworklet", "document", "embed", "font", "frame", "iframe", "image", "json", "manifest", "object", "paintworklet", "report", "script", "sharedworker", "style", "text", "track", "video", "worker", "xslt" };
enum RequestMode { "navigate", "same-origin", "no-cors", "cors" };
enum RequestCredentials { "omit", "same-origin", "include" };
enum RequestCache { "default", "no-store", "reload", "no-cache", "force-cache", "only-if-cached" };
enum RequestRedirect { "follow", "error", "manual" };
enum RequestDuplex { "half" };
enum RequestPriority { "high", "low", "auto" };
```
--------------------------------
### Response constructor
Source: https://fetch.spec.whatwg.org/
Creates a new Response object representing an HTTP response.
```APIDOC
## Response constructor
### Description
Creates a new Response object representing an HTTP response.
### Method
constructor
### Parameters
- **body** (BodyInit?) - Optional - The response body.
- **init** (ResponseInit) - Optional - An object containing response options.
### Request Example
```js
const response = new Response("Hello", {status: 200});
```
### Response
#### Success Response
Returns a new Response object.
```
--------------------------------
### Response.json(data, init)
Source: https://fetch.spec.whatwg.org/
Creates a Response whose body is the JSON-encoded data. The init parameter can specify status, statusText, and headers.
```APIDOC
## Response.json(data, init)
### Description
Creates a Response whose body is the JSON-encoded data. The init parameter can specify status, statusText, and headers.
### Method
Static
### Parameters
#### Body
- **data** (any) - Required - The data to be JSON-encoded as the response body.
#### Init (ResponseInit)
- **status** (unsigned short) - Optional - The HTTP status code. Default is 200. Must be in the range 200 to 599 inclusive.
- **statusText** (ByteString) - Optional - The status message. Default is empty string. Must match the reason-phrase token production if non-empty.
- **headers** (HeadersInit) - Optional - The response headers.
### Request Example
```javascript
const jsonResponse = Response.json({ message: 'Hello' }, { status: 200 });
```
### Response
Returns a new Response object with the JSON-encoded body.
```
--------------------------------
### Consume response body fully
Source: https://fetch.spec.whatwg.org/
Steps to fetch a request and consume the entire response body as a byte sequence.
```text
1. Let request be a request whose URL is https://stuff.example.com/ and client is this’s relevant settings object.
2. Fetch request, with _processResponseConsumeBody_ set to the following steps given a response response and null, failure, or a byte sequence contents:
1. If contents is null or failure, then present an error to the user.
2. Otherwise, parse contents considering the metadata from response, and perform your own operations on it.
```
--------------------------------
### Process response chunk-by-chunk
Source: https://fetch.spec.whatwg.org/
Steps to stream a response by processing it chunk-by-chunk using the _processResponse_ argument.
```text
1. Let request be a request whose URL is https://stream.example.com/ and client is this’s relevant settings object.
2. Fetch request, with _processResponse_ set to the following steps given a response response:
1. If response is a network error, then present an error to the user.
2. Otherwise, if response’s status is not an ok status, present some fallback value to the user.
3. Otherwise, get a reader for response’s body’s stream, and process in an appropriate way for the MIME type identified by extracting a MIME type from response’s headers list.
```
--------------------------------
### Response.json(data, init)
Source: https://fetch.spec.whatwg.org/
Static method that creates a Response object with a JSON body. It serializes the given data to JSON bytes, extracts the body, and initializes the response with the provided init options.
```APIDOC
## Response.json(data, init)
### Description
Static method that creates a Response object with a JSON body. It serializes the given data to JSON bytes, extracts the body, and initializes the response with the provided init options.
### Method
STATIC
### Endpoint
Response.json(data, init)
### Parameters
- **data** (any) - Required - The JavaScript value to serialize to JSON.
- **init** (ResponseInit) - Optional - Initialization options for the Response.
### Response
Returns a Response object with the JSON body and content type application/json.
```
--------------------------------
### Request constructor
Source: https://fetch.spec.whatwg.org/
Constructs a new Request object from an input (Request object or URL string) and an optional init dictionary. It initializes the request's method, headers, body, signal, and other properties, throwing TypeError for invalid combinations.
```APIDOC
## Request constructor
### Description
Constructs a new Request object from an input (Request object or URL string) and an optional init dictionary. It initializes the request's method, headers, body, signal, and other properties, throwing TypeError for invalid combinations.
### Method
constructor
### Parameters
#### init dictionary
- **method** (string) - Optional - The request method (e.g., GET, POST).
- **headers** (Headers or sequence) - Optional - Headers to set on the request.
- **body** (BodyInit) - Optional - The request body.
- **signal** (AbortSignal) - Optional - An abort signal to control the request.
- **priority** (RequestPriority) - Optional - The request priority.
- **duplex** (string) - Optional - The duplex mode (e.g., 'half').
### Behavior
- If init["signal"] exists, sets the signal.
- If init["priority"] exists, updates internal priority or sets priority.
- Sets this's request to the constructed request.
- Creates a dependent abort signal from the signal.
- Sets this's headers to a new Headers object with guard "request".
- If mode is "no-cors", throws TypeError if method is not CORS-safelisted, and sets headers guard to "request-no-cors".
- If init is not empty, processes headers: copies, sets from init["headers"], empties, and fills.
- If body is provided and method is GET or HEAD, throws TypeError.
- If body is provided, extracts body and sets Content-Type header if not present.
- If body is non-null and source is null, throws TypeError if duplex is missing or mode is not same-origin/cors, and sets use-CORS-preflight flag.
- If initBody is null and inputBody is non-null, creates a proxy for inputBody.
- Sets this's request's body to finalBody.
```
--------------------------------
### Fetch request with credentials
Source: https://fetch.spec.whatwg.org/
Performing a fetch request that includes credentials.
```javascript
fetch(url, { credentials:"include" }).then(success, failure)
```
--------------------------------
### fetch()
Source: https://fetch.spec.whatwg.org/
The fetch() method is a low-level API for fetching resources. It returns a Promise that resolves to a Response object, which can be used to extract the body as a Blob, JSON, or stream.
```APIDOC
## fetch()
### Description
The fetch() method is a low-level API for fetching resources. It returns a Promise that resolves to a Response object, which can be used to extract the body as a Blob, JSON, or stream.
### Method
GET
### Endpoint
fetch(resource, options)
### Parameters
#### resource (RequestInfo) - Required - The resource to fetch, typically a URL string or a Request object.
#### options (RequestInit) - Optional - An object containing custom settings for the request, such as method, headers, mode, etc.
### Request Example
fetch("/music/pk/altes-kamuffel.flac")
.then(res => res.blob()).then(playBlob)
### Response
Returns a Promise that resolves to a Response object. The Response object provides methods to access the body content, such as blob(), json(), text(), and body.getReader().
```
--------------------------------
### Request constructor
Source: https://fetch.spec.whatwg.org/
Creates a new Request object representing an HTTP request.
```APIDOC
## Request constructor
### Description
Creates a new Request object representing an HTTP request.
### Method
constructor
### Parameters
- **input** (RequestInfo) - Required - A Request object or a URL string.
- **init** (RequestInit) - Optional - An object containing request options.
### Request Example
```js
const request = new Request("https://example.com", {method: "POST", body: "data"});
```
### Response
#### Success Response
Returns a new Request object.
```
--------------------------------
### Fetch API Credentials Configuration
Source: https://fetch.spec.whatwg.org/
Modern approach for setting the credentials mode to include using the fetch API.
```JavaScript
fetch("./", { credentials:"include" }).then(/* … */)
```
--------------------------------
### Quota usage across same-origin and cross-origin documents
Source: https://fetch.spec.whatwg.org/
Demonstrates how same-origin documents share parent quota while cross-origin iframes receive a default 8kb limit, causing the final call to throw.
```javascript
// In main page
fetchLater("https://a.example.com", {method: "POST", body: a_64kb_body});
// In same-origin nested document
fetchLater("https://b.example.com", {method: "POST", body: a_64kb_body});
// In cross-origin nested document at https://fratop.example.com
fetchLater("https://a.example.com", {body: a_5kb_body});
fetchLater("https://a.example.com", {body: a_12kb_body});
```
--------------------------------
### Basic fetch request
Source: https://fetch.spec.whatwg.org/
A standard fetch request from foo.invalid to bar.invalid.
```javascript
var url = "https://bar.invalid/api?key=730d67a37d7f3d802e96396d00280768773813fbe726d116944d814422fc1a45&data=about:unicorn";
fetch(url).then(success, failure)
```
--------------------------------
### Response.redirect(url, status)
Source: https://fetch.spec.whatwg.org/
Returns a new Response object that redirects to the given URL.
```APIDOC
## Response.redirect(url, status)
### Description
Returns a new Response object that redirects to the given URL.
### Method
redirect (static)
### Parameters
- **url** (USVString) - Required - The URL to redirect to.
- **status** (unsigned short) - Optional - The HTTP status code (default 302).
### Request Example
```js
const redirectResponse = Response.redirect("https://example.com", 301);
```
### Response
#### Success Response
- **response** (Response) - A Response object with the redirect status and Location header.
```
--------------------------------
### Sequence of fetchLater() calls exceeding reporting-origin quota
Source: https://fetch.spec.whatwg.org/
The first two requests succeed, but the third call throws because it exceeds the 64 kibibytes reporting-origin quota for https://a.example.com.
```javascript
fetchLater("https://a.example.com", {method: "POST", body: a_64kb_body});
fetchLater("https://b.example.com", {method: "POST", body: a_64kb_body});
fetchLater("https://a.example.com");
```
--------------------------------
### Log a response header
Source: https://fetch.spec.whatwg.org/
Uses the HEAD method to fetch headers and log a specific header value.
```javascript
fetch("/", {method:"HEAD"})
.then(res => log(res.headers.get("strict-transport-security")))
```
--------------------------------
### Headers constructor
Source: https://fetch.spec.whatwg.org/
Creates a new Headers object, optionally initialized with a HeadersInit value.
```APIDOC
## Headers constructor
### Description
Creates a new Headers object, optionally initialized with a HeadersInit value.
### Method
constructor
### Parameters
#### Optional Parameters
- **init** (HeadersInit) - Optional - A sequence of name-value pairs or a record of key-value strings to initialize the headers with.
### Request Example
```js
const headers = new Headers({"Content-Type": "application/json"});
```
### Response
#### Success Response
Returns a new Headers object.
```
--------------------------------
### getSetCookie()
Source: https://fetch.spec.whatwg.org/
Returns the values of all Set-Cookie headers in order. Returns an empty list if no Set-Cookie header exists.
```APIDOC
## getSetCookie()
### Description
Returns the values of all Set-Cookie headers in order. Returns an empty list if no Set-Cookie header exists.
### Method
getSetCookie
### Returns
- A list of values of all Set-Cookie headers, in order. Empty list if none.
```
--------------------------------
### Inspect Response Type via JavaScript
Source: https://fetch.spec.whatwg.org/
Demonstrates how to access the 'type' property of a Response object to identify if it is default, basic, cors, opaque, or opaqueredirect.
```javascript
console.log(new Response().type); // "default"
console.log((await fetch("/")).type); // "basic"
console.log((await fetch("https://api.example/status")).type); // "cors"
console.log((await fetch("https://crossorigin.example/image", { mode: "no-cors" })).type); // "opaque"
console.log((await fetch("/surprise-me", { redirect: "manual" })).type); // "opaqueredirect"
```
--------------------------------
### Response.redirect(url, status)
Source: https://fetch.spec.whatwg.org/
Creates a redirect Response that redirects to the given URL with the specified status. The status must be a redirect status (301, 302, 303, 307, or 308).
```APIDOC
## Response.redirect(url, status)
### Description
Creates a redirect Response that redirects to the given URL with the specified status. The status must be a redirect status (301, 302, 303, 307, or 308).
### Method
Static
### Parameters
#### Path Parameters
- **url** (USVString) - Required - The URL to redirect to.
- **status** (unsigned short) - Optional - The HTTP status code. Default is 302. Must be a redirect status.
### Request Example
```javascript
const redirectResponse = Response.redirect('https://example.com', 302);
```
### Response
Returns a new Response object with the Location header set to the given URL and the specified status.
```
--------------------------------
### XMLHttpRequest Credentials Configuration
Source: https://fetch.spec.whatwg.org/
Legacy method for setting the credentials mode to include using XMLHttpRequest.
```JavaScript
var client = new XMLHttpRequest()
client.open("GET", "./")
client.withCredentials = true
/* … */
```
--------------------------------
### Body.text()
Source: https://fetch.spec.whatwg.org/
Returns a promise that resolves with the body as a UTF-8 decoded string.
```APIDOC
## Body.text()
### Description
Returns a promise that resolves with the body as a UTF-8 decoded string.
### Method
text()
### Returns
Promise resolving to a USVString.
```
--------------------------------
### BodyInit Type Definitions
Source: https://fetch.spec.whatwg.org/
Defines the union types for BodyInit, which can accept various data formats including Blobs, BufferSources, FormData, URLSearchParams, and strings.
```webidl
typedef (Blob or BufferSource or FormData or URLSearchParams or USVString) XMLHttpRequestBodyInit;
typedef (ReadableStream or XMLHttpRequestBodyInit) BodyInit;
```
--------------------------------
### response.clone()
Source: https://fetch.spec.whatwg.org/
Returns a clone of the response. The clone has the same body, status, and headers as the original.
```APIDOC
## response.clone()
### Description
Returns a clone of the response. The clone has the same body, status, and headers as the original.
### Method
Instance method
### Parameters
None
### Request Example
```javascript
const clonedResponse = response.clone();
```
### Response
Returns a new Response object that is a clone of the original.
```
--------------------------------
### Request.clone()
Source: https://fetch.spec.whatwg.org/
Returns a new Request object that is a clone of the current request.
```APIDOC
## Request.clone()
### Description
Returns a new Request object that is a clone of the current request.
### Method
clone()
### Returns
A new Request object.
```
--------------------------------
### set(name, value)
Source: https://fetch.spec.whatwg.org/
Sets a header value, replacing any existing header with the same name. Validates and respects the request-no-cors guard.
```APIDOC
## set(name, value)
### Description
Sets a header value, replacing any existing header with the same name. Validates and respects the request-no-cors guard.
### Method
set
### Parameters
- **name** (string) - Required - The header name.
- **value** (string) - Required - The header value.
### Behavior
- Normalizes the value.
- If validation fails, returns.
- If guard is "request-no-cors" and (name, value) is not no-CORS-safelisted, returns.
- Sets the header in the header list.
- If guard is "request-no-cors", removes privileged no-CORS request-headers.
```
--------------------------------
### Headers.get(name)
Source: https://fetch.spec.whatwg.org/
Returns the value of a header, or null if the header is not present.
```APIDOC
## Headers.get(name)
### Description
Returns the value of a header, or null if the header is not present.
### Method
get
### Parameters
- **name** (ByteString) - Required - The name of the header to retrieve.
### Request Example
```js
const value = headers.get("Content-Type");
```
### Response
#### Success Response
- **value** (ByteString?) - The header value, or null if not found.
```
--------------------------------
### Fetch API Interface Definitions
Source: https://fetch.spec.whatwg.org/
Defines the fetch() method within WindowOrWorkerGlobalScope and the fetchLater() method for deferred requests.
```webidl
partial interface mixin WindowOrWorkerGlobalScope {
[NewObject] Promise fetch(RequestInfo input, optional RequestInit init = {});
};
dictionary DeferredRequestInit : RequestInit {
DOMHighResTimeStamp activateAfter;
};
[Exposed=Window]
interface FetchLaterResult {
readonly attribute boolean activated;
};
partial interface Window {
[NewObject, SecureContext] FetchLaterResult fetchLater(RequestInfo input, optional DeferredRequestInit init = {});
};
```
--------------------------------
### Headers.set(name, value)
Source: https://fetch.spec.whatwg.org/
Sets a new value for an existing header or adds the header if it does not exist.
```APIDOC
## Headers.set(name, value)
### Description
Sets a new value for an existing header or adds the header if it does not exist.
### Method
set
### Parameters
- **name** (ByteString) - Required - The name of the header.
- **value** (ByteString) - Required - The value to set.
### Request Example
```js
headers.set("Content-Type", "application/json");
```
### Response
#### Success Response
No return value (undefined).
```
--------------------------------
### Response.headers getter
Source: https://fetch.spec.whatwg.org/
Getter that returns the response's headers.
```APIDOC
## Response.headers getter
### Description
Getter that returns the response's headers.
### Method
GETTER
### Endpoint
Response.headers
### Response
Returns the response's headers.
```
--------------------------------
### FetchLaterResult.activated
Source: https://fetch.spec.whatwg.org/
A getter that returns a boolean indicating whether the deferred fetch has been activated.
```APIDOC
## FetchLaterResult.activated
### Description
A getter that returns a boolean indicating whether the deferred fetch has been activated.
### Method
activated getter
### Return Value
Returns a boolean.
### Example
```
function check_if_fetched() {
return result.activated;
}
```
```
--------------------------------
### Request.clone()
Source: https://fetch.spec.whatwg.org/
Creates a clone of the Request object.
```APIDOC
## Request.clone()
### Description
Creates a clone of the Request object.
### Method
clone
### Parameters
None.
### Request Example
```js
const clonedRequest = request.clone();
```
### Response
#### Success Response
- **clone** (Request) - A new Request object that is a clone of the original.
```
--------------------------------
### Request clone() method
Source: https://fetch.spec.whatwg.org/
Creates a clone of the Request object. Throws TypeError if the request is unusable. Returns a new Request object with the same request, headers guard, and a dependent abort signal.
```APIDOC
## Request clone() method
### Description
Creates a clone of the Request object. Throws TypeError if the request is unusable. Returns a new Request object with the same request, headers guard, and a dependent abort signal.
### Method
clone()
### Behavior
1. If this is unusable, throw a TypeError.
2. Let clonedRequest be the result of cloning this's request.
3. Assert: this's signal is non-null.
4. Let clonedSignal be the result of creating a dependent abort signal from this's signal.
5. Let clonedRequestObject be the result of creating a Request object with clonedRequest, this's headers's guard, clonedSignal, and this's relevant realm.
6. Return clonedRequestObject.
```
--------------------------------
### Response.clone()
Source: https://fetch.spec.whatwg.org/
Creates a clone of the Response object.
```APIDOC
## Response.clone()
### Description
Creates a clone of the Response object.
### Method
clone
### Parameters
None.
### Request Example
```js
const clonedResponse = response.clone();
```
### Response
#### Success Response
- **clone** (Response) - A new Response object that is a clone of the original.
```
--------------------------------
### Response.error()
Source: https://fetch.spec.whatwg.org/
Creates a network error Response object. This is a static method that returns a Response representing a network error.
```APIDOC
## Response.error()
### Description
Creates a network error Response object. This is a static method that returns a Response representing a network error.
### Method
Static
### Parameters
None
### Request Example
```javascript
const errorResponse = Response.error();
```
### Response
Returns a new Response object representing a network error.
```
--------------------------------
### Request getters
Source: https://fetch.spec.whatwg.org/
Getter methods that return properties of the Request object, such as method, url, headers, destination, referrer, referrerPolicy, mode, credentials, cache, redirect, integrity, keepalive, isReloadNavigation, isHistoryNavigation, signal, and duplex.
```APIDOC
## Request getters
### Description
Getter methods that return properties of the Request object, such as method, url, headers, destination, referrer, referrerPolicy, mode, credentials, cache, redirect, integrity, keepalive, isReloadNavigation, isHistoryNavigation, signal, and duplex.
### Getter: method
Returns this's request's method.
### Getter: url
Returns this's request's URL, serialized.
### Getter: headers
Returns this's headers.
### Getter: destination
Returns this's request's destination.
### Getter: referrer
Returns this's request's referrer. If referrer is "no-referrer", returns empty string. If "client", returns "about:client". Otherwise, returns serialized referrer.
### Getter: referrerPolicy
Returns this's request's referrer policy.
### Getter: mode
Returns this's request's mode.
### Getter: credentials
Returns this's request's credentials mode.
### Getter: cache
Returns this's request's cache mode.
### Getter: redirect
Returns this's request's redirect mode.
### Getter: integrity
Returns this's request's integrity metadata.
### Getter: keepalive
Returns this's request's keepalive.
### Getter: isReloadNavigation
Returns true if this's request's reload-navigation flag is set; otherwise false.
### Getter: isHistoryNavigation
Returns true if this's request's history-navigation flag is set; otherwise false.
### Getter: signal
Returns this's signal.
### Getter: duplex
Returns "half".
```
--------------------------------
### bytes()
Source: https://fetch.spec.whatwg.org/
Returns a promise that resolves with a Uint8Array containing the body data. Can reject with a RangeError.
```APIDOC
## bytes()
### Description
Returns a promise that resolves with a Uint8Array containing the body data. Can reject with a RangeError.
### Method
GET
### Endpoint
requestOrResponse.bytes()
### Parameters
None
### Response
Returns a Promise that resolves with a Uint8Array.
```
--------------------------------
### Response.ok getter
Source: https://fetch.spec.whatwg.org/
Getter that returns true if the response's status is an ok status (200-299), otherwise false.
```APIDOC
## Response.ok getter
### Description
Getter that returns true if the response's status is an ok status (200-299), otherwise false.
### Method
GETTER
### Endpoint
Response.ok
### Response
Returns a boolean.
```
--------------------------------
### response.url
Source: https://fetch.spec.whatwg.org/
Returns the response's URL, if it has one; otherwise the empty string. This is a read-only property.
```APIDOC
## response.url
### Description
Returns the response's URL, if it has one; otherwise the empty string. This is a read-only property.
### Method
Property (read-only)
### Parameters
None
### Request Example
```javascript
const url = response.url;
```
### Response
Returns a USVString.
```
--------------------------------
### Response.url getter
Source: https://fetch.spec.whatwg.org/
Getter that returns the response's URL, serialized without the fragment. If the URL is null, returns the empty string.
```APIDOC
## Response.url getter
### Description
Getter that returns the response's URL, serialized without the fragment. If the URL is null, returns the empty string.
### Method
GETTER
### Endpoint
Response.url
### Response
Returns the serialized URL string, or empty string if URL is null.
```
--------------------------------
### response.ok
Source: https://fetch.spec.whatwg.org/
Returns whether the response's status is an ok status (200-299). This is a read-only property.
```APIDOC
## response.ok
### Description
Returns whether the response's status is an ok status (200-299). This is a read-only property.
### Method
Property (read-only)
### Parameters
None
### Request Example
```javascript
const ok = response.ok;
```
### Response
Returns a boolean.
```
--------------------------------
### Response.type getter
Source: https://fetch.spec.whatwg.org/
Getter that returns the response's type.
```APIDOC
## Response.type getter
### Description
Getter that returns the response's type.
### Method
GETTER
### Endpoint
Response.type
### Response
Returns the response's type.
```
--------------------------------
### response.type
Source: https://fetch.spec.whatwg.org/
Returns the response's type, such as 'cors', 'basic', 'error', etc. This is a read-only property.
```APIDOC
## response.type
### Description
Returns the response's type, such as 'cors', 'basic', 'error', etc. This is a read-only property.
### Method
Property (read-only)
### Parameters
None
### Request Example
```javascript
const type = response.type;
```
### Response
Returns a ResponseType enum value.
```
--------------------------------
### Receive body data progressively
Source: https://fetch.spec.whatwg.org/
Uses a reader to consume the response body stream in chunks.
```javascript
function consume(reader) {
var total = 0
return pump()
function pump() {
return reader.read().then(({done, value}) => {
if (done) {
return
}
total += value.byteLength
log(`received ${value.byteLength} bytes (${total} bytes in total)`)
return pump()
})
}
}
fetch("/music/pk/altes-kamuffel.flac")
.then(res => consume(res.body.getReader()))
.then(() => log("consumed the entire body without keeping the whole thing in memory!"))
.catch(e => log("something went wrong: " + e))
```
--------------------------------
### arrayBuffer()
Source: https://fetch.spec.whatwg.org/
Returns a promise that resolves with an ArrayBuffer containing the body data. Can reject with a RangeError.
```APIDOC
## arrayBuffer()
### Description
Returns a promise that resolves with an ArrayBuffer containing the body data. Can reject with a RangeError.
### Method
GET
### Endpoint
requestOrResponse.arrayBuffer()
### Parameters
None
### Response
Returns a Promise that resolves with an ArrayBuffer.
```
--------------------------------
### response.redirected
Source: https://fetch.spec.whatwg.org/
Returns whether the response was obtained through a redirect. This is a read-only property.
```APIDOC
## response.redirected
### Description
Returns whether the response was obtained through a redirect. This is a read-only property.
### Method
Property (read-only)
### Parameters
None
### Request Example
```javascript
const redirected = response.redirected;
```
### Response
Returns a boolean.
```
--------------------------------
### Terminate fetch with unobservable reader
Source: https://fetch.spec.whatwg.org/
The user agent can terminate the fetch because the termination cannot be observed.
```javascript
fetch("https://www.example.com/").then(res => res.body.getReader().closed)
```