The JavaScript Fetch API is a modern, promise-based system for making network requests. This API is superior to the outdated XMLHttpRequest, which is more complicated to use and doesn't provide the benefits of promises.
The Fetch API is a simple and logical way to fetch resources asynchronously across a network. It will seem familiar to anyone who has used XMLHttpRequest, but the new API provides a more powerful and flexible feature set.
fetch('https://api.example.com/data', {
method: 'GET',
headers: {
'Content-Type': 'application/json',
}
})
.then(response => response.json())
.then(data => console.log(data))
.catch((error) => {
console.error('Error:', error);
});
The fetch()
function returns a Promise
that resolves to the Response object representing the response to the request. This response could be success, failure, or anything else.
A common misconception is that fetch() will reject the promise if the HTTP status is an error. It's not true. fetch() will only reject the promise if there's a network error.
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch((error) => {
console.error('There has been a problem with your fetch operation:', error);
});
In the above example, we are checking the ok property of the Response object to check if the HTTP response status is in the successful range.
The fetch() function accepts two arguments: the path to the resource you want to fetch, and an options object.
fetch(url, options);
The options object can contain the following:
And that's it! That's your introduction to the Fetch API in JavaScript. With it, you can make promise-based network requests in the browser and in Node.js.