The Fetch API is a browser - based API that provides an interface for fetching resources (including across the network). It uses the fetch()
method to initiate a network request and returns a Promise
that resolves to the Response
object representing the response to the request. The fetch()
method takes at least one argument, the URL of the resource you want to fetch, and can optionally take a second argument, an options object to customize the request.
The simplest way to use the Fetch API is to make a GET request to a server. Here is a basic example:
// Make a GET request to a JSONPlaceholder API endpoint
fetch('https://jsonplaceholder.typicode.com/todos/1')
.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 this example, we call the fetch()
method with the URL of a JSON API. The fetch()
method returns a Promise
that resolves to the Response
object. We then check if the response was successful using the ok
property of the Response
object. If it was successful, we call the json()
method on the Response
object, which returns another Promise
that resolves to the JSON data. Finally, we log the data to the console or catch any errors that occurred during the process.
The Response
object returned by the fetch()
method contains several useful properties and methods. Here are some of the most commonly used ones:
ok
: A boolean indicating whether the response was successful (status code in the range 200 - 299).status
: The HTTP status code of the response.statusText
: The status message corresponding to the status code.headers
: An object representing the headers of the response.json()
: A method that returns a Promise
that resolves to the JSON data in the response body.text()
: A method that returns a Promise
that resolves to the text data in the response body.blob()
: A method that returns a Promise
that resolves to a Blob
object representing the binary data in the response body.Here is an example of using the text()
method to handle a response:
fetch('https://example.com/plain - text')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.text();
})
.then(text => {
console.log(text);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
The fetch()
method can be used to make different types of HTTP requests by passing an options object as the second argument. Here is an example of making a POST request:
const data = {
title: 'foo',
body: 'bar',
userId: 1
};
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify(data)
})
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(newData => {
console.log(newData);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
In this example, we pass an options object to the fetch()
method. The method
property specifies the HTTP method (in this case, POST
). The headers
property is an object containing the headers of the request. We set the Content - Type
header to application/json
because we are sending JSON data. The body
property contains the data we want to send, which we first convert to a JSON string using the JSON.stringify()
method.
As shown in the previous examples, we can use the catch()
method to handle errors that occur during the fetch
operation. Errors can occur due to various reasons, such as network issues, server errors, or invalid URLs. It’s important to handle errors gracefully in your application to provide a better user experience.
fetch('https://nonexistent - api.com')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
async/await
syntax can make your code more readable and easier to understand when working with the Fetch API. Here is the previous GET request example rewritten using async/await
:async function fetchData() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/todos/1');
if (!response.ok) {
throw new Error('Network response was not ok');
}
const data = await response.json();
console.log(data);
} catch (error) {
console.error('There has been a problem with your fetch operation:', error);
}
}
fetchData();
fetch()
method does not have a built - in timeout option. You can use the AbortController
API to set a timeout for your requests.const controller = new AbortController();
const signal = controller.signal;
setTimeout(() => {
controller.abort();
}, 5000);
fetch('https://example.com', { signal })
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => {
console.log(data);
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('Fetch aborted due to timeout');
} else {
console.error('There has been a problem with your fetch operation:', error);
}
});
The Fetch API is a powerful and flexible tool for making network requests in JavaScript. It provides a modern, promise - based approach that simplifies the process of interacting with web services. By understanding the fundamental concepts, usage methods, and best practices outlined in this guide, you should be able to use the Fetch API effectively in your own projects.