Поиск  
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
Источник:
Просмотров:
1865

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
Похожее
Jun 2, 2022
Author: Anthony Rodge
Backend frameworks are the most critical building blocks that make application development easier and practical. Most developers, and clients for whom the developers create apps, have a problem choosing a backed framework. For a long time, .NET has played a...
Mar 23, 2022
Why do we need lifecycle hooks? Modern front-end frameworks move the application from state to state. Data fuels these updates. These technologies interact with the data which in turn transitions the state. With every state change, there are many specific...
Oct 31
Author: Dante J. Anjos
In this post I want to show how we can easily create a modal with vanilla JavaScript. It can have multiple open/close handlers thanks to querySelectorAll. First of all lets create the HTML structure for our modal. <div class="modal">  ...
Nov 24, 2023
Author: Swathi Kashettar
This article offers insights and career guidance on data science and software engineer The tech industry offers a plethora of exciting career opportunities, and two of the most in-demand professions are software engineering and data science. While both roles involve...
Написать сообщение
Тип
Почта
Имя
*Сообщение