Fetch API: A modern replacement for XMLHttpRequest
By: Vrijraj Singh
Tags: Codingurukul, JavaScript, Fetch, Fetchapi

It is said that “Necessity is the mother of all inventions” and that’s what fueled the development of Fetch API. But before digging deeper into the Fetch API let’s dive into the history behind it. I know I know what’s going on in your mind but I will keep it short.

Fetch is a new native JavaScript API, supported by most browsers today. Fetch allows you to make network requests similar to XMLHttpRequest . According to Google Developers Documentation Fetch makes it easier to make asynchronous requests and handle responses better than with the older XMLHttpRequest . It is an improvement over the XMLHttpRequest API. The main difference between Fetch and XMLHttpRequest is that the Fetch API uses Promises, hence avoiding callback hell.

Fetch Interfaces

The Fetch API has following interfaces

fetch() : The fetch() method used to fetch a resource.

: The method used to fetch a resource. Headers : Represents response/request headers, allowing you to query them and take different actions depending on the results.

: Represents response/request headers, allowing you to query them and take different actions depending on the results. Request : Represents a resource request.

: Represents a resource request. Response : Represents the response to a request.

Making a request using fetch()

A fetch() function is available in the global window object. The fetch() function takes one mandatory argument, the path to the resource you want to fetch. It returns a Promise , whether it is successful or not. If request is successful .then() function will receive Response object, if request fails then .catch() function will receive an error object

The Response Object

The above code makes use of Fetch API and makes a call to GitHub to fetch data about the user. When the promise is resolved we get a Response object in return. But wait, if you try logging Response object on the console you will find that it didn’t have the data which we want. That’s because a Response object has information about the response itself. To actually get the data, we need to get the body of the response.

Headers Object

The Headers interface allows you to create your own headers object via the Headers() constructor. A headers object is a collection of name-value pairs.

var headers = new Headers();

headers.append('Content-Type', 'text/json');

headers.append('X-Custom-Header', 'SomeValue');



//We can achieve the same can by passing an object literal to the constructor



var headers = new Headers({

'Content-Type': 'text/json',

'X-Custom-Header': 'SomeValue'

});

Supplying options to fetch()

The fetch() method accepts an optional second parameter, an init object that allows you to customise the request.

let reqHeader = new Headers();

reqHeader.append('Content-Type', 'text/json');

method: 'GET', headers: reqHeader,

};



fetch('

.then(function (response) {

return response.json();

})

.then(function (data) {

console.log(data);

})

.catch(function (err) {

console.log("Something went wrong!", err);

}); let initObject = {method: 'GET', headers: reqHeader,};fetch(' https://api.github.com/users ', initObject).then(function (response) {return response.json();}).then(function (data) {console.log(data);}).catch(function (err) {console.log("Something went wrong!", err);});

Request Object

The Request Object represents a resource request. Instead of passing an URL of the resource into the fetch() call, you can create a request object using the Request() constructor, and pass that as an argument to fetch(). By passing Request object to the fetch() , you can make customised requests.



reqHeader.append('Content-Type', 'text/json');



let initObject = {

method: 'GET', headers: reqHeader,

};



var userRequest = new Request('



fetch(userRequest)

.then(function (response) {

return response.json();

})

.then(function (data) {

console.log(data);

})

.catch(function (err) {

console.log("Something went wrong!", err);

}); let reqHeader = new Headers();reqHeader.append('Content-Type', 'text/json');let initObject = {method: 'GET', headers: reqHeader,};var userRequest = new Request(' https://api.github.com/users ', initObject);fetch(userRequest).then(function (response) {return response.json();}).then(function (data) {console.log(data);}).catch(function (err) {console.log("Something went wrong!", err);});

Definitely, The Fetch API makes it easier to make asynchronous requests and handle responses better than using an XMLHttpRequest . Fetch allows us to create a better API for the simple things, using modern JavaScript features like promises .

Let’s start fetching !!

References

Thanks

Happy Coding!