Axios vs fetch API vs XMLHttpRequest – how to make a remote call on Vue.js (and not only)

What is this article about

Most websites present external data fetch from REST or AJAX API. This article presents the pros and cons of three methods of how to play with remote APIs. The examples use Vue.js as the base framework, but the methods are universal and can be used in any other JavaScript framework.

Time to read: 3 min

Author: Piotr Krupa, Lead Web Developer @ Eversis

Developing programming and coding technologies. Website design. Cyberspace concept.

How to make a remote call

Most of the presently developed web pages fetch and push the data by remote APIs. Asynchronous Javascript and XML (AJAX) requests are as old as web development dinosaurs, remembering the ancient browsers such as Netscape Navigator. 

Such a trivial issue like remote calls should be resolved for many years in the current age. It is. How? Let’s go through typical approaches to remote API calls, starting with the most precious one: Axios. 

What the Axios is

Axios is an open-source, AJAX application programming interface wrapper, which simplifies the development of remote calls. The web developers community likes this library for two reasons: it relies on the Promise API and supports most common browsers. In addition, Axion works well if you need to run it on the servers side, on Node.js. 

The mechanics of Axion relies on XMLHttpRequest wrapped in a friendly way. On Node.js, it covers “HTTP” requests. 

But most importantly, as I wrote before – it’s easy to write and understand. Here is an example of how to make a simple GET request.

Axios( url ) 
.then( response-handler ) 
.catch( error-handler ) 
.finally( final-handler ) 

.finally( final-handler ) 

As a promised based API, it allows passing three types of handlers:  

  • then – executed after correctly receiving the response,  
  • catch – when any error occurs, 
  • finally – after execution of both previews 

But, wait! Why use the external library if the native one works well?

I am a purist. I use only native API.

Web browsers implement two native ways to do remote calls: XMLHttpRequest and Fetch API. 

XMLHttpRequest 

I am not sure if XMLHttpRequest creators lived at the same ages that creators of Netscape Navigator, but the method they created is mature. All widely used browsers support that way of remote calls. But? 

The first issue is that XMLHttpRequest becomes deprecated in Java Script Specification (ES6). Consequently, in the next few years, the new releases of popular browsers can terminate the support for this method. 

Another problem is that the XMLHttpRequest is quite raw. To make a request, you must write many lines of code. XMLHttpRequest does not support promises. In consequence, that complex request chains require more nested handlers, which complicates the code. How does the request look like? 

        var xhr = new XMLHttpRequest(); 
	var movies = []; 
	xhr.open("GET", "https://ghibliapi.herokuapp.com/films"); 
	xhr.onreadystatechange = function () { 
  	if (xhr.readyState === 4 ) { // readyState 4 - the request is done. 
    	      if (xhr.status === 200 ) { // status 200 is a successful return. 
      	         movies = JSON.parse(xhr.responseText); 
    	      } else { 
      	      console.log("Error: " + xhr.status); 
    	      } 
  	    } 
	}; 
	xhr.send(null);

Imagine writing the following API call to fetch information about actors and directors from Studio Ghibli API. It becomes a nightmare

Fetch API 

Instead of XMLHttpRequest, the ES6 JavaScript specification provides a nice, promised oriented fetch function. The code looks pretty and similar to Axion: 

fetch('https://ghibliapi.herokuapp.com/films') 
  	.then(response => response.json()) 
  	.then(data => this.movies = data ) ; 

Unfortunately, this option is not perfect as well. Older browsers do not support the fetch function, not to mention Internet Explorer, which generally does not support the procedure. 

The response from the web development community was immediate. The fetch API polyfill resolves the incompatibility problem. But it is the external library, like Axion.

How does it work? Working example.

To provide you with the working example, I will use the call from previews chapters and display the results in the list. To render the list, I will use a simple Vuejs application. 

Step 1: Vue and Axion  

Import both libraries in the head section: 

<script src='https://cdnjs.cloudflare.com/ajax/libs/vue/2.6.11/vue.min.js'> </script>   	
<script src='https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js'></script> 

Step 2: Write the template for rendering the list: 

h1>List of Studio Ghibli Movies</h1> 
<div><img width="300" src="http://ghibliapi.herokuapp.com/images/logo.svg"/</div> 
<div id="app">   
  <ol v-cloak v-if="movies!=null"> 
	<li v-for="movie in movies"> 
  	{{ movie.title }} [{{movie.release_date}}] 
	</li> 
  </ol> 
</div> 

Step 3: Write the Vuejs app and make a request:

var app = new Vue({ 
  el: "#app", 
  data: { 
	movies: null 
  }, 
  mounted() { 
	axios.get("https://ghibliapi.herokuapp.com/films") 
  	.then( response => this.movies = response.data ) 
  	.catch( error => console.log( 'error: ' + error ) ); 
  } 
}); 

That’s all, folks. Pure and simple. 

To play with the code, you can use the working example on CodePen: https://codepen.io/eversis/pen/eYgqYYb. You can see also: 

Summary 

Axion provides a straightforward method for fetching data from external APIs. What is more, the library also unifies external calls for all browsers and Node.js. 

From the other perspective, the Fetch API provides the same benefits. Until it is not widely supported, Axion is an obvious alternative. In the future, the library can be an efficient solution for moving to Fetch API smoothly. 

If you still insist on using Fetch API, you can use a polyfill provided here: https://github.com/github/fetch

Additionally, the library provides many valuable futures, which helps develop web applications, for instance: 

  • globally scoped configuration, which allows to set-up parameters (headers, base URL, authorisation tokens) in one place  
  • interceptors – allowing intercept requests and responses before handling 
  • cancellation – enabling abandonment of the request on user requests 

It does not mean that Fetch API does not support those functions. But I AxionAxion they look more clear in my opinion. 

References  

Are you Vue.js enthusiast?

We continuously search for technology enthusiasts which want to grow in our web development team. Visit eversis.com/career to see job positions in our Warsaw, Szczecin or Wroclaw offices. We are open for remote employees from whole Europe.

Contact us!

Want to hire us or just have a question? Share your email and we will come back to you in two days.