Window: fetch() method
BaselineWidely available *
This feature is well established and works across many devices and browser versions. It’s been available across browsers since March 2017.
* Some parts of this feature may have varying levels of support.
Thefetch()
method of theWindow
interface starts the process of fetching a resource from the network, returning a promise that is fulfilled once the response is available.
The promise resolves to theResponse
object representing the response to your request.
Afetch()
promise only rejects when the request fails, for example, because of a badly-formed request URL or a network error.Afetch()
promisedoes not reject if the server responds with HTTP status codes that indicate errors (404
,504
, etc.).Instead, athen()
handler must check theResponse.ok
and/orResponse.status
properties.
Thefetch()
method is controlled by theconnect-src
directive ofContent Security Policy rather than the directive of the resources it's retrieving.
Note:Thefetch()
method's parameters are identical to those of theRequest()
constructor.
Syntax
fetch(resource)fetch(resource, options)
Parameters
resource
This defines the resource that you wish to fetch. This can either be:
- A string or any other object with astringifier — including a
URL
object — that provides the URL of the resource you want to fetch. The URL may be relative to the base URL, which is the document'sbaseURI
in a window context, orWorkerGlobalScope.location
in a worker context. - A
Request
object.
- A string or any other object with astringifier — including a
options
OptionalA
RequestInit
object containing any custom settings that you want to apply to the request.
Return value
Exceptions
AbortError
DOMException
The request was aborted due to a call to the
AbortController
abort()
method.NotAllowedError
DOMException
Thrown if use of theTopics API is specifically disallowed by a
browsing-topics
Permissions Policy, and afetch()
request was made withbrowsingTopics: true
.TypeError
Can occur for the following reasons:
Reason | Failing examples |
---|---|
Blocked by a permissions policy | Use of theAttribution Reporting API is blocked by aattribution-reporting Permissions-Policy , and afetch() request was made withattributionReporting specified. |
Invalid header name. | js
|
Invalid header value. The header object must contain exactly two elements. | js
|
Invalid URL or scheme, or using a scheme that fetch does not support, or using a scheme that is not supported for a particular request mode. | js
|
URL includes credentials. | js
|
Invalid referrer URL. | js
|
Invalid modes (navigate andwebsocket ). | js
|
If the request cache mode is "only-if-cached" and the request mode is other than "same-origin". | js
|
If the request method is an invalid name token or one of the forbidden headers (CONNECT ,TRACE orTRACK ). | js
|
If the request mode is "no-cors" and the request method is not a CORS-safe-listed method (GET ,HEAD , orPOST ). | js
|
If the request method isGET orHEAD and the body is non-null or not undefined. | js
|
If fetch throws a network error. |
Examples
In ourFetch Request example (seeFetch Request live) wecreate a newRequest
object using the relevant constructor, then fetch itusing afetch()
call. Since we are fetching an image, we runResponse.blob()
on the response to give it the proper MIME type so it will behandled properly, then create an Object URL of it and display it in an<img>
element.
const myImage = document.querySelector("img");const myRequest = new Request("flowers.jpg");window .fetch(myRequest) .then((response) => { if (!response.ok) { throw new Error(`HTTP error! Status: ${response.status}`); } return response.blob(); }) .then((response) => { myImage.src = URL.createObjectURL(response); });
In ourFetch Request with init example (seeFetch Request init live) we do the same thing except that we pass in anoptions object when we invokefetch()
.In this case, we can set aCache-Control
value to indicate what kind of cached responses we're okay with:
const myImage = document.querySelector("img");const reqHeaders = new Headers();// A cached response is okay unless it's more than a week oldreqHeaders.set("Cache-Control", "max-age=604800");const options = { headers: reqHeaders,};// Pass init as an "options" object with our headers.const req = new Request("flowers.jpg", options);fetch(req).then((response) => { // …});
You could also pass theinit
object in with theRequest
constructor to get the same effect:
const req = new Request("flowers.jpg", options);
You can also use an object literal asheaders
ininit
:
const options = { headers: { "Cache-Control": "max-age=60480", },};const req = new Request("flowers.jpg", options);
TheUsing fetch article provides more examples of usingfetch()
.
Specifications
Specification |
---|
Fetch # fetch-method |