How does the fetch API work in JavaScript?
fetch takes a URL and gives you back a promise. That promise resolves with a Response object. The request is sent in the background, so the code that called it carries on straight away and deals with the outcome later. Because the request is asynchronous, the promise almost always resolves with the response headers first, and you read the body as a separate step afterwards.
// The Response object is what fetch resolves with.
// You can build one locally to try this without a network.
const response = new Response(JSON.stringify({ name: 'Ada', id: 7 }), {
status: 200,
headers: { 'Content-Type': 'application/json' },
});
async function readProfile() {
// A real call would be: const response = await fetch('/api/profile');
if (!response.ok) {
throw new Error('Request failed with status ' + response.status);
}
return response.json();
}
readProfile()
.then(function (profile) {
console.log(profile.name, profile.id);
})
.catch(function (error) {
console.log('failed:', error.message);
});
Two parts of the API catch people out on their first use. The body has to be read on purpose, and you read it exactly once, with the method that matches its type. Use the json method for JSON, the text method for text, and the blob or arrayBuffer methods for binary data. The body is a stream, so trying to read it a second time fails.
The second part is the options object. It carries the method, the headers, the body, and the credentials mode. For anything other than a simple GET request, the body has to be a string, a URL encoded form, a Blob, or an array buffer. Sending a plain object does not turn it into a request body for you. You have to call the json method on the request options, or you have to turn the object into text yourself.
fetch also supports an abort signal, and that is how you cancel a request that you no longer need. You create an abort controller, and when you abort it the fetch promise rejects with an abort error. The browser also stops the network request itself instead of only ignoring the result.