Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
April 28, 2023 06:23 am GMT

How JavaScript's Fetch API works under the hood

Introduction

Fetch API is a modern web API that provides a way to fetch resources asynchronously over the network. It has become a popular choice for fetching data and resources in web applications due to its simplicity, flexibility, and consistency. In this article, well take a look at how Fetch API works under the hood and explore its core features.

How Fetch API works ?

Fetch API is based on the Promise API, which provides a consistent and elegant way to handle asynchronous operations in JavaScript. When you call the fetch() function, it returns a Promise object that resolves with a Response object if the request is successful, or rejects with an error if the request fails.

Under the hood, Fetch API uses the XMLHttpRequest object to send HTTP requests and receive responses from the server. XMLHttpRequest is a low-level API that has been around since the early days of the web and is used by many other web APIs, including AJAX and WebSockets.

When you call fetch(), it creates a new XMLHttpRequest object and sets up event listeners to handle the response from the server. The fetch() function also takes an optional options object that allows you to customize the HTTP request, including the HTTP method, headers, and body.

Heres an example of how to use the Fetch API to fetch a resource over the network:

fetch('https://abc.com/data.json')  .then(response => response.json())  .then(data => console.log(data))  .catch(error => console.error(error));

In this example, were using fetch() to fetch a JSON file from the server. Once the response is received, we call the json() method on the Response object to extract the JSON data from the response. We then log the data to the console. If an error occurs, we log the error to the console.

Fetch API also supports a variety of HTTP methods, including GET, POST, PUT, DELETE, and others. You can specify the HTTP method using the options object, like this:

fetch('https://abc.com/data.json', {  method: 'POST',  body: JSON.stringify({ foo: 'bar' }),  headers: {    'Content-Type': 'application/json'  }}).then(response => console.log(response)).catch(error => console.error(error));

In this example, were using fetch() to send a POST request to the server with a JSON payload. We're setting the Content-Type header to application/json to indicate that the payload is JSON data.

Fetch API also supports a variety of other features, including request and response headers, request and response modes, cookies, and more.

Simplified Implementation

Heres a simplified JavaScript implementation of the Fetch API that explains how it works under the hood:

function fetch(url, options) {  // create a new Promise object  return new Promise((resolve, reject) => {    // create a new XMLHttpRequest object    const xhr = new XMLHttpRequest();    // handle the response from the server    xhr.onload = () => {      const response = new Response(xhr.responseText, {        status: xhr.status,        statusText: xhr.statusText,        headers: xhr.getAllResponseHeaders()      });      resolve(response);    };    // handle any errors that occur while fetching    xhr.onerror = () => {      reject(new TypeError('Network request failed'));    };    // open the connection to the server    xhr.open(options.method || 'GET', url);    // set any headers that were provided    for (const header in options.headers) {      xhr.setRequestHeader(header, options.headers[header]);    }    // send the request to the server    xhr.send(options.body);  });}

This implementation of the Fetch API uses the XMLHttpRequest object, which is the low-level networking API that underlies most modern web APIs. Heres a breakdown of how it works:

  • The fetch() function takes two arguments: the URL of the resource to fetch and an options object that contains any additional information about the request (such as headers, the HTTP method to use, and the body of the request).
  • The fetch() function creates a new Promise object and returns it. The Promise will resolve with a Response object if the request is successful, or reject with an error if the request fails.
  • The fetch() function creates a new XMLHttpRequest object, which will be used to send the actual HTTP request to the server.
  • The xhr.onload() function is called when the response from the server is received. This function creates a new Response object, which is populated with the response data (the response body, headers, status code, and status text). The Response object is then passed to the resolve() function, which resolves the Promise that was returned by fetch().
  • The xhr.onerror() function is called if an error occurs while fetching the resource. This function creates a new TypeError object with the message "Network request failed", and passes it to the reject() function, which rejects the Promise that was returned by fetch().
  • The xhr.open() function is used to open a connection to the server. It takes two arguments: the HTTP method to use (which defaults to "GET" if none is provided), and the URL of the resource to fetch.
  • The xhr.setRequestHeader() function is used to set any headers that were provided in the options object. This is done by iterating over the properties of the options.headers object and setting each header in turn.
  • The xhr.send() function is used to send the actual HTTP request to the server. If the request has a body, it is passed as an argument to the send() function.

This implementation of the Fetch API is simplified and doesnt include all of the features of the actual Fetch API, but it should give you an idea of how it works under the hood.

Conclusion

Fetch API provides a powerful and flexible way to fetch resources over the network in web applications. Under the hood, it uses the XMLHttpRequest object to send HTTP requests and receive responses from the server. By using Promises and a consistent API, Fetch API makes it easy to handle asynchronous operations in JavaScript. With its support for HTTP methods, headers, and other features, Fetch API has become a popular choice for fetching data and resources in modern web applications.


Original Link: https://dev.to/leduc1901/how-javascripts-fetch-api-works-under-the-hood-3n9p

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To