Open In App

fetch API in JavaScript with Examples

Improve
Improve
Improve
Like Article
Like
Save Article
Save
Share
Report issue
Report

The JavaScript fetch() method is used to fetch resources from a server. It returns a Promise that resolves to the Response object representing the response to the request.

The fetch method can also make HTTP requests- GET request (to get data) and POST request (to post data). Fetch also integrates advanced HTTP concepts such as CORS and other extensions to HTTP.

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

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. 

Example 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:

get request in fetch method javascript

Explanation:

  1. 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.
  2. 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.
  3. 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()

Example 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.

Example 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.

1. How to use JavaScript Fetch API to Get Data

JavaScript Get request is used to retrieve Data from a server. To use the Fetch API in JavaScript to get data from a server, you can make a GET request to the desired URL and handle the response.

2. Get and Post method using Fetch API

A fetch() method can be used with any type of request such as POST, GET, PUT, and DELETE, GET method uses fetch API

3. Difference between Fetch and Axios for making http requests

Axios is a stand-alone third-party package that can be easily installed and Fetch is built into most modern browsers; no installation is required as such.

Supported Browsers:

fetch() is an ECMAScript6 (ES6) feature and is supported on almost all modern browsers like:



Last Updated : 15 Mar, 2024
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads