No More Dreaded XHR! Fetch API Is Here

Introduction

 
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, the 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.   
  5. function success(data) {  
  6.  ...  
  7. }  
  8.   
  9. function error() {  
  10.  ...  
  11. }  
  12.   
  13. function canceled() {  
  14.  ...  
  15. }  
  16.   
  17. var req = new XMLHttpRequest();  
  18. req.addEventListener("progress", progress);  
  19. req.addEventListener("load", success);  
  20. req.addEventListener("error", error);  
  21. req.addEventListener("abort", canceled);  
  22.   
  23. req.open("GET""/GetData");  
  24. 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(() => {  
  2.  ...  
  3. }).catch(() => {  
  4.  ...  
  5. }) 
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 the JSON result.
 
There are a 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 creates a clone of the response.
     
  • formData()
    Returns a Promise that resolves with FormData object.
     
  • json()
    Returns a promise with a 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 the above example, we saw how to 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: '[email protected]',  
  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.