Search  
Always will be ready notify the world about expectations as easy as possible: job change page
Aug 15

Fetch API in JavaScript with examples

Fetch API in JavaScript with examples
Source:
Views:
1864

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.

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.

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

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

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

  • Google Chrome
  • Edge
  • Firefox
  • Opera
  • Safari
Similar
Mar 11
Author: Zafer Ayan Zafer Ayan
The Fetch vs Axios debate has been going on for years and recently it has come up again. I will talk about the disadvantages of using the Fetch API directly instead of using a network library like Axios. First of...
Feb 18, 2023
Author: Adnan Puzic
Good UX design happens when you don’t notice it during or after the experience. The main goal of good UX design is to take the user on a specific mission as quickly as possible, with the least effort possible. In...
Apr 18
Author: Michael Shpilt
One of the most used databases these days is PostgreSQL (aka Postgres). Its accomplishments include being the most popular DB [among professional developers] according to Stack Overflow survey of 2022, the database in all of the fastest TechEmpower benchmarks, and...
Jul 30
Author: Emer Kurbegovic
Azure Cosmos DB is a globally distributed, multi-model database service provided by Microsoft Azure. It supports multiple data models, including document, key-value, graph, and column-family data models. In this article, we’ll explore how to add and retrieve data from Azure...
Send message
Type
Email
Your name
*Message