Skip to content

Fetch Method for Ajax

fetch() sends an HTTP request and returns a promise. The promise resolves to a Response object as soon as the server’s reply starts to arrive, and the body is then read with a method such as response.json() or response.text(), each of which returns a promise of its own.

fetch() is built into every current browser and into Node.js 18 and later. Older tutorials install the node-fetch package to use it in Node, but that is no longer needed. The examples use JSONPlaceholder, a free service that returns sample users, posts and tasks.

The Response carries the status and the headers before the body has been read.

const response = await fetch('https://jsonplaceholder.typicode.com/users/2');
console.log(response.status, response.ok);
console.log(response.headers.get('content-type'));
const user = await response.json();
console.log(user.name, user.address.city);

This prints:

200 true
application/json; charset=utf-8
Ervin Howell Wisokyburgh

response.ok is true for any status from 200 to 299, so it is a better test than comparing the status with 200. The body can be read only once, so a second call to response.json() returns a promise that rejects with a TypeError.

fetch() rejects only when no response arrives at all, for example when the network is down or the host does not exist. A reply of 404 or 500 is still a response, so the promise resolves and the code has to check the status itself. A common pattern is to throw an error when response.ok is false, so that both kinds of failure end up in the same catch.

const getUser = async (id) => {
const response = await fetch(`https://jsonplaceholder.typicode.com/users/${id}`);
if (!response.ok) {
throw new Error(`Request for user ${id} failed with status ${response.status}`);
}
return response.json();
};
for (const id of [5, 42]) {
try {
const user = await getUser(id);
console.log(`Found ${user.name}`);
} catch (err) {
console.log(err.message);
}
}

This prints:

Found Chelsey Dietrich
Request for user 42 failed with status 404

When the request cannot be sent at all, fetch() rejects with a TypeError:

try {
await fetch('https://no-such-host.invalid/data');
} catch (err) {
console.log(err.name, err.message);
}

This prints:

TypeError fetch failed

The message differs between environments, and browsers usually say Failed to fetch or NetworkError when attempting to fetch resource, so code should not depend on its wording.

The same request can be written as a promise chain, which is how most older code uses fetch(). Each then() receives what the previous one returned, and a single catch() at the end handles a failure at any step.

fetch('https://jsonplaceholder.typicode.com/posts/1')
.then((response) => {
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
return response.json();
})
.then((post) => console.log(post.title))
.catch((err) => console.log('Request failed:', err.message));

This prints:

sunt aut facere repellat provident occaecati excepturi optio reprehenderit

A second argument, an options object, changes the request. To send JSON, set the method, say what the body contains in a Content-Type header, and turn the object into a string with JSON.stringify().

const newTask = { title: 'Buy bread', completed: false, userId: 3 };
const response = await fetch('https://jsonplaceholder.typicode.com/todos', {
method: 'POST',
headers: { 'Content-Type': 'application/json' },
body: JSON.stringify(newTask),
});
console.log(response.status);
console.log(await response.json());

This prints:

201
{ title: 'Buy bread', completed: false, userId: 3, id: 201 }

Status 201 means Created. JSONPlaceholder only pretends to save the task, so it returns the object with a new id but does not store it.

In the browser, the data usually ends up on the page. This snippet loads a user when the button is clicked and writes the name into a paragraph.

<button id="load-user">Load user 3</button>
<p id="user-name"></p>
const button = document.getElementById('load-user');
const output = document.getElementById('user-name');
button.addEventListener('click', async () => {
output.textContent = 'Loading…';
try {
const response = await fetch('https://jsonplaceholder.typicode.com/users/3');
if (!response.ok) {
throw new Error(`HTTP ${response.status}`);
}
const user = await response.json();
output.textContent = `${user.name} lives in ${user.address.city}`;
} catch (err) {
output.textContent = `Could not load the user: ${err.message}`;
}
});

Clicking the button shows Loading… and then Clementine Bauch lives in McKenziehaven. Setting textContent rather than innerHTML keeps any markup in the data from being run as HTML.

In the browser, a request to another domain also has to be allowed by that server under the CORS rules. JSONPlaceholder allows requests from any page, but many APIs do not, and a blocked request rejects in the same way as a network failure. The MDN guide to using fetch covers the other options, such as headers, credentials and cancelling a request with an AbortController.

Steve Griffith covers this topic in his video Fundamentals of the JavaScript fetch method for AJAX.