No More Dreaded XHR! Fetch API Is Here

We all are aware of JavaScript's dreaded XMLHttprequest (XHR) request. Some developers are using XHR requests even today, which involves some very messy code. And really, XHR request is not a pretty JavaScript code. It might be possible that you are using jQuery to send the XHR which is cleaner but not the best.
 
jQuery XHR Request Syntax
  1. jQuery.ajax({  
  2.    ...  
  3. })   
Now, we have JavaScript's built-in Fetch API by which you can make requests similar to that of XHR.
 
Fetch API 

Fetch API allows you to make network requests similar to XHR. It has a new standard jam-packed way to make the request, which also uses promises. 
 
Before starting with Fetch API, let's understand how XHR request works.
 
Using XMLHttpRequest

To send an HTTP request, first, we create XMLHttpRequest Object. By this object, we open the connection using the URL and send the request. After the transaction completes, we also create some event listeners by which we get the response back with HTTP Status Code.
 
XMLHttpRequest Example
  1. function progress() {  
  2.     ...  
  3. }  
  4. function success(data) {  
  5.     ...  
  6. }  
  7. function error() {  
  8.     ...  
  9. }  
  10. function canceled() {  
  11.     ...  
  12. }  
  13.   
  14. var req= new XMLHttpRequest();  
  15. req.addEventListener("progress", progress);  
  16. req.addEventListener("load", success);  
  17. req.addEventListener("error", error);  
  18. req.addEventListener("abort", canceled);  
  19.   
  20. req.open("GET""/GetData");  
  21. req.send();  
XMLHttpRequest with jQuery 

The following example shows how you can send xhr request using jQuery.
  1. jQuery.ajax({  
  2.     url:url,  
  3.     type:'POST',  
  4.     data:JSON.stringify(data),  
  5.     dataType:'json',  
  6.     contenttype:'application/json',  
  7.     beforeSend:function(xhr){  
  8.         ...  
  9.     },  
  10.     success:function(data){  
  11.         ...  
  12.     },  
  13.     error:function(data){  
  14.         ...  
  15.     },  
  16.     complete:function(){  
  17.         ...  
  18.     }  
  19. })  
How do we use the fetch API?

In a very simple manner, we can call Fetch API with URL only. By default, the Fetch API uses the GET verb. Let's look at a very simple single line example:
 
Simple fetch API syntax 
  1. fetch(url).then(() => {...}).catch(()=>{...})  
Let's understand what syntax is.
  1. fetch(url)// Here we are calling the fetch function with URL where we want to request, This URL may be api URL  
  2. .then((data) => {  
  3.    //Here you will write your code according to data which you will get after API call  
  4. })  
  5. .catch((err) => {  
  6.     // This part will run when server will return any errors  
  7. })  
Example
  1. fetch('https://freegeoip.net/json/github.com')  
  2.        .then((res) => res.json())  
  3.        .then((data)=>console.log(data))   
Above example's link is as follows - Fetch API to Get Data
 
Let's understand the above code.  In the above code, first, we are calling Fetch API and passing it to the URL. We are not passing more parameters, so by default, the call will be a GET call. Then, we get a response but it is not JSON but an object. So, we are converting the object into JSON using the json() method. Then, we are printing JSON result.
 
There are series of methods like json() which we can use depending on the situation, what we want to do with the information. Those methods are as follows,
  • arrayBuffer() 
    Returns a promise object with an Array Buffer.

  • blob() 
    Returns a promise object with a blob object.

  • clone() 
    This ceates a clone of the response.

  • formData()
    Returns a promise that resolves with FormData object.

  • json()
    Returns a promise with JSON object.

  • redirect()
    This method creates a new response but with a different url.

  • text()
    This method is used when want to resolve object into text.
In above example, we saw how GET the data using Fetch API. Now I know you are excited and thinking about POST, PUT and DELETE calls. I am going to explain POST calls; then I know you will be able to call any http verb. 
 
POST call using Fetch API

By default fetch API uses GET request. You can use the following syntax for the POST call.
  1. const url='<URL>';  
  2.   
  3. let data={  
  4.     name:'sourabh somani',  
  5.     email:'sourabh_somani2010@hotmail.com',  
  6.     mobile:'9314554546'  
  7. };  
  8.   
  9. fetch(url, {   
  10.     method: 'POST',   
  11.     body: data,  
  12.     headers: new Headers()  
  13. }).then(function(res){  
  14.     // do whatever you want to do after success  
  15. }).catch(function(err) {  
  16.     // Error when API send any error  
  17. });  
Note
If your browser doesn't support fetch api then polyfill is available here : A window.fetch JavaScript polyfill 
 
You can read more about fetch api from the following links,
  • https://developers.google.com/web/updates/2015/03/introduction-to-fetch
  • https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API 
Conclusion

Fetch API is better and simpler to use than XHR. So, don't use XMLHttpRequest anymore. Instead, you can use Fetch API.