Mastering Fetch API in JavaScript

Mastering Fetch API in JavaScript

A Comprehensive Guide for Beginners

Fetch API

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

  • The fetch API can perform all the tasks that the XMLHttpRequest (XHR) object does.

  • The fetch API is much simpler and cleaner.

  • It uses the promise to deliver a more flexible feature to make requests to servers from web browsers.

Sending a request

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

  • The fetch() method requires only one parameter, which is the URL of the resource that you want to fetch.

  • When the request is complete, the promise will resolve into a response object.

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 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(), formData(), and arrayBuffer() to handle the respective type of data.

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

async function fetchText() {
let response = await fetch('/readme.txt');
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 fetch('/reademe.txt');

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

    if(response.status == 200) {
        let data = await response.text(); // handle the data
    }
}
fetchText();

Did you find this article valuable?

Support Sandip Halder by becoming a sponsor. Any amount is appreciated!