Fetch is a new-ish, promise-based API that lets us do Ajax requests without all the fuss associated with XMLHttpRequest. As you’ll see in this post, Fetch is very easy to use and work with and greatly simplifies fetching resources from an API. Plus, it’s now supported in all modern browsers, so using Fetch is really a no-brainer.
Let’s demonstrate a simple GET request by going and GET ourselves some dummy data from the JSONPlaceholder API:
fetch('https://jsonplaceholder.typicode.com/users')
.then(res => res.json())
.then(res => res.map(user => user.username))
.then(userNames => console.log(userNames));
And the output will be an array of user names like this:
["Bret", "Antonette", "Samantha", "Karianne", "Kamren", "Leopoldo_Corkery", "Elwyn.Skiles", "Maxime_Nienow", "Delphine", "Moriah.Stanton"]
Given that we expect a JSON response, we first need to call the json() method to transform the Response object into an object that we can interact with. The text()
could be used if we expected an XML response instead.
To make requests other than GET, pass-in an object as a second argument to a fetch call with the method to use as well as any needed headers and the body of the request:
const myPost = {
title: 'A post about true facts',
body: '42',
userId: 2
}
const options = {
method: 'POST',
body: JSON.stringify(myPost),
headers: {
'Content-Type': 'application/json'
}
};
fetch('https://jsonplaceholder.typicode.com/posts', options)
.then(res => res.json())
.then(res => console.log(res));
JSONPlaceholder sends us the POSTed data back with an ID attached:
Object {
body: 42,
id: 101,
title: "A post about true facts",
userId: 2
}
You’ll note that the request body needs to be stringified. Other methods that you can use for fetch calls are DELETE, PUT, HEAD and OPTIONS
There’s a catch (pun intended 😉) when it comes to error handling with the Fetch API: if the request properly hits the endpoint and comes back, no error will be thrown. This means that error handling is not as simple as chaining a catch call at then end of your fetch promise chain.
Luckily though, the response object from a fetch call has an ok property that will be either true of false depending on the success of the request. You can then use Promise.reject() if ok is false:
fetch('https://jsonplaceholder.typicode.com/postsZZZ', options)
.then(res => {
if (res.ok) {
return res.json();
} else {
return Promise.reject({ status: res.status, statusText: res.statusText });
}
})
.then(res => console.log(res))
.catch(err => console.log('Error, with message:', err.statusText));
With the above example our promise will reject because we’re calling an endpoint that doesn’t exist. The chained catch call will be hit and the following will be outputted:
"Error, with message: Not Found"
Since Fetch is a promise-based API, using async functions is a great option to make your code even easier to reason about and synchronous-looking. Here for example is an async/await function that performs a simple GET request and extracts the usernames from the returned JSON response to then log the result at the console:
async function fetchUsers(endpoint) {
const res = await fetch(endpoint);
let data = await res.json();
data = data.map(user => user.username);
console.log(data);
}
fetchUsers('https://jsonplaceholder.typicode.com/users');
Or, you could just return a promise from your async/await function and then you’d have the ability to keep-on chaining then calls after calling the function:
async function fetchUsers(endpoint) {
const res = await fetch(endpoint);
const data = await res.json();
return data;
}
fetchUsers('https://jsonplaceholder.typicode.com/users')
.then(data => {
console.log(data.map(user => user.username));
});
Calling json() returns a promise so in the above example, when we return data
in the async function, we’re returning a promise.
And then again you could also throw an error if the response’s ok is false and catch the error as usual in your promise chain:
async function fetchUsers(endpoint) {
const res = await fetch(endpoint);
if (!res.ok) {
throw new Error(res.status); // 404
}
const data = await res.json();
return data;
}
fetchUsers('https://jsonplaceholder.typicode.com/usersZZZ')
.then(data => {
console.log(data.map(user => user.website));
})
.catch(err => console.log('Ooops, error', err.message));
Ooops, error 404
Browser Support
Can I Use fetch? Data on support for the fetch feature across the major browsers from caniuse.com.
Thanks for learning with the DigitalOcean Community. Check out our offerings for compute, storage, networking, and managed databases.
While we believe that this content benefits our community, we have not yet thoroughly reviewed it. If you have any suggestions for improvements, please let us know by clicking the “report an issue“ button at the bottom of the tutorial.
This textbox defaults to using Markdown to format your answer.
You can type !ref in this text area to quickly search our full set of tutorials, documentation & marketplace offerings and insert the link!
Calling json() returns a promise so in the above example, when we return data in the async function, we’re returning a promise. The note is NOT correct. calling json() doesn’t return a promise but rather a regular object, BUT since the funcitons is async it will always return a promise (it wraps whatever it returns into a promise).