fetch API in JavaScript with Examples
Last Updated :
09 Oct, 2024
The fetch() method in JavaScript is a modern and powerful way to retrieve resources from a server. It returns a Promise that resolves to a Response object, encapsulating the server’s response to your request.
Furthermore, fetch() seamlessly integrates advanced HTTP functionalities such as Cross-Origin Resource Sharing (CORS) and other extensions, enriching the web development experience with enhanced security and interoperability.
Note: Fetch API comes with the fetch() method, which is used to fetch data from different sources.
Syntax:
fetch('url') // api for the get request
.then(response => response.json())
.then(data => console.log(data));Parameters:
- URL: The URL to which the request is to be made.
- Options: It is an array of properties. It is an optional parameter. Options available are:
- Method: Specifies HTTP method for the request. (can be GET, POST, PUT or DELETE)
- Headers
- Body: Data to be sent with the request.
- Mode: Specifies request mode(eg. cors, nocors, same-origin, etc)
- Credentials: Specifies whether to send user credentials (cookies, authentication headers, etc.) with the request
To deepen your understanding of how to use the fetch() API effectively, check out our JavaScript Course, which includes practical examples and projects centered around working with APIs and asynchronous data fetching.
JavaScript fetch() Method Examples
Let’s look at some of the examples of the fetch method. These examples provide you with a complete understanding of the fetch method in JavaScript.
1. Get Request Using Fetch
This example shows how to make Get request in fetch method.
Note: Without options, Fetch will always act as a get request.
JavaScript
// API for get requests
let fetchRes = fetch(
"https://jsonplaceholder.typicode.com/todos/1");
// FetchRes is the promise to resolve
// it by using.then() method
fetchRes.then(res =>
res.json()).then(d => {
console.log(d)
})
Output:

Explanation:
- The JS fetch() function is used to send a GET request to the URL “https://jsonplaceholder.typicode.com/todos/1”. This function returns a Promise that resolves to a Response object representing the response to the request.
- The then() method is chained to the fetch() call to handle the response asynchronously. Inside the callback function passed to then(), the res.json() method is called to parse the response body as JSON. This method also returns a Promise that resolves to the parsed JSON data.
- Another then() method is chained to handle the parsed JSON data. Inside its callback function, the parsed JSON data d is logged to the console using console.log()
2. Using fetch to Post JSON Data
In this example, we have uploaded JSON data using the fetch() API in JavaScript, you can set the request body to a JSON stringified version of your data and set the appropriate headers to indicate that you’re sending JSON.
Post requests can be made using fetch by giving the options given below:
let options = {
method: 'POST',
headers: {
'Content-Type': 'application/json;charset=utf-8'
},
body: JSON.stringify(data)
}After checking the Syntax of the post request, look at the example below which demonstrates using post request in fetch method.
JavaScript
// Your JSON data
const jsonData = { key1: 'value1', key2: 'value2' };
// Set up options for the fetch request
const options = {
method: 'POST',
headers: {
'Content-Type': 'application/json' // Set content type to JSON
},
body: JSON.stringify(jsonData) // Convert JSON data to a string and set it as the request body
};
// Make the fetch request with the provided options
fetch('https://api.example.com/upload', options)
.then(response => {
// Check if the request was successful
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the response as JSON
return response.json();
})
.then(data => {
// Handle the JSON data
console.log(data);
})
.catch(error => {
// Handle any errors that occurred during the fetch
console.error('Fetch error:', error);
});
Explanation:
- We define your JSON data.
- We set up options for the fetch request, including the method set to ‘POST’, the Content-Type header set to ‘application/json’, and the body set to the JSON stringified version of your data.
- We make the fetch request with the provided options using the fetch() function.
- The rest of the code remains the same as before, handling the response and any errors that occur during the fetch.
3. Aborting a Fetch Request
You can use the AbortController and AbortSignal Interface to abort a fetch request in JavaScript.
JavaScript
// Create a new AbortController instance
const controller = new AbortController();
const signal = controller.signal;
// Make the fetch request with the signal
const fetchPromise = fetch('https://api.example.com/data', { signal });
// Timeout after 5 seconds
const timeoutId = setTimeout(() => {
controller.abort(); // Abort the fetch request
console.log('Fetch request timed out');
}, 5000);
// Handle the fetch request
fetchPromise
.then(response => {
// Check if the request was successful
if (!response.ok) {
throw new Error('Network response was not ok');
}
// Parse the response as JSON
return response.json();
})
.then(data => {
// Handle the JSON data
console.log(data);
})
.catch(error => {
// Handle any errors that occurred during the fetch
console.error('Fetch error:', error);
})
.finally(() => {
clearTimeout(timeoutId); // Clear the timeout
});
Explanation:
- We create a new AbortController instance and obtain its signal.
- We make the fetch request using fetch() with the provided options.
- We set a timeout of 5 seconds using setTimeout() to abort the fetch request if it takes too long.
- Inside the timeout callback, we call controller.abort() to abort the fetch request.
- We handle the fetch request as usual, including parsing the response and handling any errors.
- Finally, in the finally() block, we clear the timeout using clearTimeout() to prevent the timeout from triggering if the fetch request completes before the timeout expires.
Sending a request Including Credentials
To send a request including credentials, such as cookies, in a fetch request, you can set the credentials property to include.
fetch("https://example.com", {
credentials: "include",
});If you only want to send credentials if the request URL is on the same origin as the calling script, add credentials: ‘same-origin’.
// The calling script is on the origin 'https://example.com'
fetch("https://example.com", {
credentials: "same-origin",
});
JavaScript fetch() Method Use Cases
Here are some of the use cases of the fetch method. These are common issues that beginner developers face when working with fetch.
- Retrieving Data with GET Requests: Ideal for fetching data from a server.
- Sending Data with POST Requests: Easily send data to a server by configuring the request method and body.
- Difference Between fetch() and Axios: fetch() is built into modern browsers and doesn’t require installation, unlike Axios, which is a third-party package offering additional features.
Supported Browsers
JavaScript Fetch is an ECMAScript6 (ES6) feature and is supported on almost all modern browsers like: