|
body
|
Ready-only property. Contains a readable stream of byte data with the body contents that have been added to the request.Data type/value: A ReadableStream or null.
|
```
const request = new Request("/myEndpoint", {
method: "POST",
body: "Hello world",
});
request.body; // ReadableStream
```
|
|
bodyUsed
|
Ready-only property. Flag that indicates whether the request body has been read yet.Accepted value:
- true: The request body has been read.
- false: The request body hasn't been read.
Data type: Boolean
|
```
const request = new Request("/myEndpoint", {
method: "POST",
body: "Hello world",
});
request.bodyUsed; // false
request.text().then((bodyAsText) => {
console.log(request.bodyUsed); // true
});
```
|
|
cache
|
Ready-only property. Contains the cache mode of the request which controls how the request interacts with the browser's HTTP cache. Accepted values:
- default: The browser looks for a matching request in its HTTP cache.
- If there is a match and it is fresh, it is returned from the cache.
- If there is a match but it is stale, the browser makes a conditional request to the remote server. If the server indicates that the resource has not changed, it is returned from the cache. Otherwise the resource is downloaded from the server and the cache will be updated.
- If there is no match, the browser makes a normal request, and updates the cache with the downloaded resource.
- force-cache: The browser looks for a matching request in its HTTP cache.
- If there is a match, fresh or stale, it is returned from the cache.
- If there is no match, the browser makes a normal request and updates the cache with the downloaded resource.
- no-cache: The browser looks for a matching request in its HTTP cache.
- If there is a match, fresh or stale, the browser makes a conditional request to the remote server. If the server indicates that the resource has not changed, it is returned from the cache. Otherwise the resource is downloaded from the server and the cache is updated.
- If there is no match, the browser makes a normal request, and updates the cache with the downloaded resource.
- no-store: The browser fetches the resource from the remote server without first looking in the cache, and does not update the cache with the downloaded resource.
- only-if-cached: The browser looks for a matching request in its HTTP cache.
- If there is a match, fresh or stale, it is returned from the cache.
- If there is no match, the browser responds with 504 Gateway timeout status.
The `only-if-cached` mode can only be used if the request's mode is `same-origin`. Cached redirects are followed if the request's `redirect` property is `follow` and the redirects do not violate the `same-origin` mode.
- reload: The browser fetches the resource from the remote server without first looking in the cache, but then updates the cache with the downloaded resource.
Data type: String
|
```
// Download a resource with cache busting, to bypass the cache
// completely.
fetch("some.json", { cache: "no-store" }).then((response) => {
/* consume the response */
});
// Download a resource with cache busting, but update the HTTP
// cache with the downloaded resource.
fetch("some.json", { cache: "reload" }).then((response) => {
/* consume the response */
});
// Download a resource with cache busting when dealing with a
// properly configured server that will send the correct ETag
// and Date headers and properly handle If-Modified-Since and
// If-None-Match request headers, therefore we can rely on the
// validation to guarantee a fresh response.
fetch("some.json", { cache: "no-cache" }).then((response) => {
/* consume the response */
});
// Download a resource with economics in mind! Prefer a cached
// albeit stale response to conserve as much bandwidth as possible.
fetch("some.json", { cache: "force-cache" }).then((response) => {
/* consume the response */
});
// Naive stale-while-revalidate client-level implementation.
// Prefer a cached albeit stale response; but update if it's too old.
// AbortController and signal to allow better memory cleaning.
// In reality; this would be a function that takes a path and a
// reference to the controller since it would need to change the value
let controller = new AbortController();
fetch("some.json", {
cache: "only-if-cached",
mode: "same-origin",
signal: controller.signal,
})
.catch((e) =>
e instanceof TypeError && e.message === "Failed to fetch"
? { status: 504 } // Workaround for chrome; which fails with a TypeError
: Promise.reject(e),
)
.then((res) => {
if (res.status === 504) {
controller.abort();
controller = new AbortController();
return fetch("some.json", {
cache: "force-cache",
mode: "same-origin",
signal: controller.signal,
});
}
const date = res.headers.get("date"),
dt = date ? new Date(date).getTime() : 0;
if (dt < Date.now() - 86_400_000) {
// if older than 24 hours
controller.abort();
controller = new AbortController();
return fetch("some.json", {
cache: "reload",
mode: "same-origin",
signal: controller.signal,
});
}
// Other possible conditions
if (dt < Date.now() - 300_000)
// If it's older than 5 minutes
fetch("some.json", { cache: "no-cache", mode: "same-origin" }); // no cancellation or return value.
return res;
})
.then((response) => {
/* consume the (possibly stale) response */
})
.catch((error) => {
/* Can be an AbortError/DOMException or a TypeError */
});
```
|
|
credentials
|
Read-only. Reflects the value given to the Request\(\) constructor in the credentials option. Credentials are cookies, TLS client certificates, or authentication headers containing a username and password.Accepted values:
- include: Always include credentials, even for cross-origin requests.
- omit: Never send credentials in the request or include credentials in the response.
- same-origin: Only send and include credentials for same-origin requests.
Data type: String
|
```
const request = new Request("flowers.jpg");
const request = request.request; // returns "same-origin" by default
```
|
|
destination
|
Read-only. Returns a string describing the type of content being requested.Accepted values:
- audio: The target is audio data.
- audioworklet: The target is data being fetched for use by an audio worklet.
- document: The target is an HTML or XML document.
- embed: The taget is embedded content.
- fencedframe: The target is a fenced frame.
- font: The target is a font.
- frame: The target is a frame.
- iframe: The target is an iframe.
- image: The target is an image.
- json: The target is a JSON file
- manifest: The target is a manifest.
- object: The target is a object.
- paintworklet: The target is a paint worklet.
- report: The target is a report.
- script: The target is a script.
- sharedworker: The target is a shared worker.
- style: The target is a style.
- track: The target is an HTML <track>.
- video: The target is video data.
- worker: The target is a worker.
- xslt: The target is an XSLT transform.
Data type: String
|
```
fetch('https://example.com/image.jpg', {
destination: 'image'
})
.then(response => response.blob())
.then(blob => {
console.log('Image fetched successfully', blob);
})
.catch(error => console.error('Error:', error));
```
|
|
headers
|
Read-only. The Headers object associated with the request.Data type: Headers object
|
```
const myRequest = new Request("flowers.jpg");
const myHeaders = myRequest.headers; // Headers {}
```
|
|
integrity
|
Read-only. The subresource integrity value of the request.Value: The value that was passed as the **options.integrity** argument when constructing the request. If an integrity has not been specified, the property returns `''`.
|
```
const myRequest = new Request("flowers.jpg", {
integrity: "sha256-abc123",
});
console.log(myRequest.integrity); // "sha256-abc123"
```
|
|
isHistoryNavigation
|
Read-only. Boolean indicating whether the request is a history navigation.Accepted values:
- true: The request is a history navigation.
- false: The request is not a history navigation.
Data type: Boolean
|
```
self.addEventListener("request", (event) => {
// ...
if (event.request.isHistoryNavigation) {
event.respondWith(
caches.match(event.request).then((response) => {
if (response !== undefined) {
return response;
} else {
return fetch(event.request).then((response) => {
let responseClone = response.clone();
caches.open("v1").then((cache) => {
cache.put(event.request, responseClone);
});
return response;
});
}
}),
);
}
// ...
});
```
|
|
keepalive
|
Read-only. The request's keepalive setting \(true or false\). Returns an empty string if an integrity value is not passed in the request.Accepted values:
- true: The browser keeps the associated request alive if the page that initiated it is unloaded before the request is complete.
- false: The browser doesn't keep the associated request alive if the page that initiated it is unloaded before the request is complete.
Data type: Boolean
|
```
const options = {
keepalive: true,
};
const myRequest = new Request("flowers.jpg", options);
let myKeepAlive = myRequest.keepalive; // true
```
|
|
method
|
Read-only. The request's method \(`GET`, `POST`, etc.\)Data type: String
|
```
const myRequest = new Request("flowers.jpg");
const myMethod = myRequest.method; // GET
```
|
|
mode
|
Read-only. Mode of the request. Used to determine if cross-origin requests lead to valid responses, and which properties of the response are readable.Accepted values:
- cors: If the request is cross-origin then it will use the Cross-Origin Resource Sharing \(CORS\) mechanism.
- navigate: A mode for supporting navigation. The navigate value is intended to be used only by HTML navigation. A navigate request is created only while navigating between documents.
- no-cors: Disables CORS for cross-origin requests. The response is opaque, meaning that its headers and body are not available to JavaScript.
- same-origin: Disallows cross-origin requests. If a request is made to another origin with this mode set, the result is an error.
Requests can be initiated in a variety of ways, and the mode for a request depends on the particular means by which it was initiated. For example, when a Request object is created using the Request\(\) constructor, the value of the mode property for that Request is set to cors. However, for requests created other than by the Request\(\) constructor, no-cors is typically used as the mode; for example, for embedded resources where the request is initiated from markup, unless the crossorigin attribute is present, the request is in most cases made using the no-cors mode — that is, for the <link> or <script> elements \(except when used with modules\), or <img>, <audio>,<video>, <object>, <embed>, or <iframe> elements.
Data type: String
|
```
const myRequest = new Request("flowers.jpg");
const myMode = myRequest.mode; // returns "cors" by default
```
|
|
redirect
|
Read-only. Mode for how redirects are handled.Valid values:
- error
- follow
- manual
Data type: String
Default: follow
|
```
const myRequest = new Request("flowers.jpg");
const myCred = myRequest.redirect;
```
|
|
referrer
|
Read-only. The referrer of the request \(for example, `client`, `no-referrer`, or a URL\). A value of `no-referrer` returns an empty string.Data type: String
|
```
const myRequest = new Request("flowers.jpg");
const myReferrer = myRequest.referrer; // returns "about:client" by default
```
|
|
referrerPolicy
|
Read-only. The referrer policy which governs what referrer information is sent in the Referrer header with the request.Data type: String
|
```
const myRequest = new Request("flowers.jpg");
const myReferrer = myRequest.referrerPolicy; // returns "" by default
```
|
|
signal
|
Read-only. AbortSignal associated with the request.Data type: String
|
```
// Create a new abort controller
const controller = new AbortController();
// Create a request with this controller's AbortSignal object
const req = new Request("/", { signal: controller.signal });
// Add an event handler logging a message in case of abort
req.signal.addEventListener("abort", () => {
console.log("abort");
});
// In case of abort, log the AbortSignal reason, if any
fetch(req).catch(() => {
if (req.signal.aborted) {
if (req.signal.reason) {
console.log(`Request aborted with reason: ${req.signal.reason}`);
} else {
console.log("Request aborted but no reason was given.");
}
} else {
console.log("Request not aborted, but terminated abnormally.");
}
});
// Actually abort the request
controller.abort();
```
|
|
url
|
Read-only. URL of the request.Data type: String
|
```
const myRequest = new Request("flowers.jpg");
const myURL = myRequest.url; // "https://github.com/mdn/dom-examples/tree/main/fetch/fetch-request/flowers.jpg"
```
|