The Fetch API provides a modern, powerful, and flexible interface for fetching resources across the network. It is a native browser API that can be used as a replacement for XMLHttpRequest (Ajax) and other third-party libraries for making network requests.
Basic Usage
A basic fetch() call is simple. It takes one mandatory argument—the path to the resource you want to fetch—and returns a Promise that resolves to the Response to that request.
fetch('https://api.github.com/users/github')
.then(response => {
// Check if the request was successful
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json(); // Parse the JSON from the response
})
.then(data => {
console.log(data);
})
.catch(error => {
console.error('There has been a problem with your fetch operation:', error);
});
Advanced POST Request Example
The fetch() method can also accept an optional second argument, an options object, that allows you to control various aspects of the request, such as the method, headers, and body.
// Example data to send
const data = {
username: 'example',
password: 'password123'
};
fetch('https://example.com/user/login', {
method: 'POST', // Specify the method
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json'
},
body: JSON.stringify(data), // Convert the JavaScript object to a JSON string
mode: 'cors', // Enable Cross-Origin Resource Sharing
cache: 'no-cache', // Do not cache the response
credentials: 'include' // Include cookies in the request
})
.then(async (response) => {
// The 'response.ok' property is a boolean that is true if the status code is in the 200-299 range.
if (!response.ok) {
// If the server returns an error, we can parse the error message from the body.
const err = await response.json();
throw new Error(err.message || 'Something went wrong');
}
// Check the content type to ensure we are getting JSON.
const contentType = response.headers.get('Content-Type');
if (contentType && contentType.includes('application/json')) {
return response.json();
} else {
throw new TypeError("Oops, we haven't got JSON!");
}
})
.then((json) => {
console.log('Success:', json);
// Do something with the successful response
})
.catch(function (error) {
console.error('Fetch Error:', error.message);
// This .catch() block handles network errors (e.g., "Failed to fetch")
// and errors thrown from the .then() blocks.
if (error.message === 'Failed to fetch') {
// Handle network unavailability
console.log('Network may not be available.');
} else {
// Handle other errors (e.g., from the server or JSON parsing)
console.log(error.message);
}
});
Explanation of Options
method: The request method, e.g.,GET,POST,PUT,DELETE.headers: An object containing request headers.Content-Typeis crucial for POST requests to tell the server what kind of data you’re sending.body: The content to send with the request. It must be a string, so we useJSON.stringify()to convert our data object.mode: Controls whether cross-origin requests are allowed.corsis the most common value.cache: Controls how the request will interact with the browser’s cache.credentials: Determines if the browser should send cookies with the request.
Error Handling
A key point to remember about fetch() is that the Promise does not reject on HTTP error statuses (like 404 or 500). It only rejects on network failure or if anything prevented the request from completing.
This is why you must always check the response.ok property to see if the request was successful.