Поиск  
Always will be ready notify the world about expectations as easy as possible: job change page
Apr 13

Fetch API in JavaScript with examples

Fetch API in JavaScript with examples
Источник:
Просмотров:
166

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
Похожее
Mar 16
Author: Winds Of Change
Performance is paramount when developing web applications. A slow, unresponsive application results in poor user experience, losing users, and possibly business. For ASP.NET Core developers, there are many techniques and best practices to optimize application performance. Let’s explore some of...
20 марта
Автор: Наталья Кайда
Самые популярные языки, технологии, инструменты и архитектурные концепции.JavaScript – по-прежнему бесспорный лидерJavaScript вызывает сложные чувства у многих разработчиков, и по разным причинам: кому-то не хватает синтаксиса для явного определения типов, на кого-то наводят тоску async/await и промисы. Альтернативные языки для...
Feb 26, 2023
Author: Ian Segers
Error handling with Async/Await in JSThis will be a small article, based on some issues I picked up during code reviews and discussions with other developers. This article is rather focused on the novice JS developers.A Simple Try CatchLet’s start...
Mar 1
IoT implies physical objects linked via wireless and wired networks. It refers to a group of internet-connected devices that communicate independently over the internet without needing a person to mediate the information exchange.You might wonder how this varies from the...
Написать сообщение
Почта
Имя
*Сообщение


© 1999–2024 WebDynamics
1980–... Sergey Drozdov
Area of interests: .NET Framework | .NET Core | C# | ASP.NET | Windows Forms | WPF | HTML5 | CSS3 | jQuery | AJAX | Angular | React | MS SQL Server | Transact-SQL | ADO.NET | Entity Framework | IIS | OOP | OOA | OOD | WCF | WPF | MSMQ | MVC | MVP | MVVM | Design Patterns | Enterprise Architecture | Scrum | Kanban