The global fetch()
method starts the process of fetching a resource from the network, returning a promise which is fulfilled once the response is available.
The promise resolves to the Response
object representing the response to your request.
A fetch()
promise only rejects when a network error is encountered (which is usually when there's a permissions issue or similar). A fetch()
promise does not reject on HTTP errors (404
, etc.). Instead, a then()
handler must check the Response.ok
and/or Response.status
properties.
WindowOrWorkerGlobalScope
is implemented by both Window
and WorkerGlobalScope
, which means that the fetch()
method is available in pretty much any context in which you might want to fetch resources.
The fetch()
method is controlled by the connect-src
directive of Content Security Policy rather than the directive of the resources it's retrieving.
Note: The fetch()
method's parameters are identical to those of the Request()
constructor.
fetch(resource)
fetch(resource, options)
A Promise
that resolves to a Response
object.
In our Fetch Request example (see Fetch Request live) we create a new Request
object using the relevant constructor, then fetch it using a fetch()
call. Since we are fetching an image, we run Response.blob()
on the response to give it the proper MIME type so it will be handled 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");
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 the Fetch with init then Request example (see Fetch Request init live), we do the same thing except that we pass in an init
object when we invoke fetch()
:
const myImage = document.querySelector("img");
const myHeaders = new Headers();
myHeaders.append("Accept", "image/jpeg");
const myInit = {
method: "GET",
headers: myHeaders,
mode: "cors",
cache: "default",
};
const myRequest = new Request("flowers.jpg");
fetch(myRequest, myInit).then((response) => {
});
You could also pass the init
object in with the Request
constructor to get the same effect:
const myRequest = new Request("flowers.jpg", myInit);
You can also use an object literal as headers
in init
.
const myInit = {
method: "GET",
headers: {
Accept: "image/jpeg",
},
mode: "cors",
cache: "default",
};
const myRequest = new Request("flowers.jpg", myInit);