Master The Fetch API In JavaScript With This Amazing Guide

Master The Fetch API In JavaScript With This Amazing Guide

Hello Everyone šŸ‘‹, JavaScript is everywhere. Millions of webpages are built on JS. In this post, you’ll learn about the JavaScript Fetch API and how to use it to make asynchronous HTTP requests.

Mastering Fetch API:

The Fetch API is a modern interface that allows you to make HTTP requests to servers from web browsers.

  • If You have worked with XMLHttpRequest (XHR) objects.
  • Fetch API can perform all the tasks as the XHR object does.
  • Fetch API is much simpler and cleaner.
  • It uses the promise to deliver more flexible features to make requests to servers from web browsers.

Sending a Request:

The fetch() method is available in the global scope that instructs the web browsers to send a request to a URL.

  • The fetch () requires only one parameter which is the URL of the resource that you want to fetch.
  • When the request completes, the promise will resolve into a Response Object.,

Example:

let response = fetch(url);

Reading the Response:

The fetch() method returns a promise so you can use the then() and catch methods to handle it.

fetch(url)
  .then((response) => {
    // handle the response
})
 .catch((error) => {
  // handle the error
});
  • If the contents of the response are in the raw text format, you can use the text() method.

The text() method returns a Promise that resolves with the complete contents of the fetched resources.

fetch('/readme.txt')
  .then(response => response.text())
  .then(data => console.log(data));

Besides the text() method, the Response object has other methods such as json(), blob(), formatData() and arrayBuffer() to handle the respective type of data.

In practice you often use the async/await with the fetch() method like this:

async function fetchText() {
  let response = await fetch('/readme.txt');y
  let data = await response.text();
  console.log(data);
}

Handling the status codes:

The Response object provides the status code and status text via the status and statusText properties.

async function fetchText() {
  let response = await fecth('readme.txt');

  console.log(response.status); //200
  console.log(response.statusText); //OK

  if (response.status === 200) {
    let data = await response.text();
  }
}

I hope you guys find this tutorial helpful, if you have any questions or any points that you want to add please share them in the comment box. If you like this tutorial please share it with your friends andĀ bookmarkĀ this site for moreĀ amazing tutorials. Thanks