Axios Library: HTTP client for Javascript

We present the Axios library that allows us to perform Ajax in a very comfortable and powerful way, to consume web services and REST APIs without using a lot of code. You can implement it in both Javascript and NodeJS.

If you want to do Ajax in Javascript, it can be a great help. It is a Javascript library capable of running both in the browser and in NodeJS, which facilitates all kinds of operations as an HTTP client.

With Axios you can make requests against a server, fully configurable, and receive the response in a simple way to process. In this article we will explain the advantages of this library, as well as some basic examples of use, with which you will be able to observe how it works.

The library is based on promises, so by using it we can generate quite neat asynchronous code. It is even capable of using Async / Await to improve the syntax, although in that case you would be forced to transpile your code to make it compatible with browsers.

Why Axios?

Axios can be useful to us in many situations… although it will not always be so necessary. It would be necessary to carefully analyze the framework in which we find ourselves to see if Axios is our best solution or not. Here are some considerations.

If you use a Javascript framework (such as or ) it is very likely that you already have an HTTP client that performs the task of making a “request” against a server and receiving the “response” in an orderly manner. But if not, performing Ajax-related operations in browsers can be a bit more complex than it should be.

Many people use Ajax-related methods to be available, but the truth is that using jQuery for this reason alone is highly inadvisable, as it is quite a heavy library, compared to Axios.

If you like to take advantage of native browser features, then your thing is to use , which is the new mechanism for implementing Ajax requests, also based on promises. However, the date API is not available in all browsers, so we need to install some polyfill. This is not a problem, since loading these polyfills is a simple task, but what can represent a complexity is using the fetch API to implement slightly more complex tasks, such as consuming REST APIs. A task that Axios makes really easy for you.

Axios is an alternative that offers several advantages:

  • Provides us with a unified API for Ajax requests
  • It is highly thought to facilitate the consumption of web services, REST APIs that return JSON data.
  • It is very easy to use and can be an ideal complement for conventional websites, where jQuery is not being used, and modern frontend applications based on libraries such as React or Polymer, which do not have in their “core” mechanisms to act as an HTTP client.
  • It has very little weight (13Kb minimized and even less if we count that the server sends it compressed), in a few Kb it will save us a lot of coding work in the applications.

Apart from , Axios is compatible with all browsers in current versions. But beware, Internet Explorer is only supported from version 11. If you want your Ajax to work in older versions of Explorer, then you are more interested in jQuery or Fetch with their corresponding polyfills.

Use Axios

We come to the practical part of this article, where you will see how to use Axios to do some tasks of accessing Ajax resources from the browser.

To work with Axios we use the . This means that, when the response from the server is received, a callback function configured in “then” will be executed, and when an error occurs (for example, a response with status 404 of resource not found) the callback function defined by the “then” will be executed. catch”. But first, let’s see how to install Axios in a project.

Install Axios

To start using this library, the easiest thing would be to have it through its CDN.

However, we can also install it via npm or Bower, and integrate it into the website or web application through our preferred build system.

npm install axios

Once installed in the browser, we have an object called “axios”, which has an API of methods to perform common HTTP operations, GET, POST…

Note: if you use it inside node.js then you will have to do the corresponding require to access the axios object. “const axios = require(‘axios’)”

Examples of working with Axios

Now let’s see small pieces of code that illustrate the use of Axios, to perform very elementary tasks, but that can give you a kick start in your learning.

We are going to see several examples of using Axios designed for the browser. In general lines we will make the Ajax request and implement the typical behavior:

  • As the request occurs we want to display a “loading…” message.
  • Once we have an answer, we want to show the content obtained, or the result of the operation, or a hypothetical error.
  • When the request is finished and the response has been obtained, both in the positive and negative cases, we want to remove the “loading…” message from the page.

We will use a series of tags in the HTML, buttons and elements where to display the output. These are the same for the three examples that you will see below.

loading…

The “loading” message is initially hidden thanks to this CSS:

Note: at the end of the article you have the complete example of the code, in case any doubts arise.

Example of Ajax access to retrieve a plain text

In this simple example we are going to make a request against our own server, to retrieve the content of a text file. It is the most basic request we can make.

var loading = document.getElementById(‘loading’); var message = document.getElementById(‘message’); var button = document.getElementById(‘ajax_load’); button.addEventListener(‘click’, function() { loading.style.display = ‘block’; axios.get(‘text.txt’, { responseType: ‘text’ }) .then(function(res) { if( res.status==200) { message.innerHTML = res.data; } console.log(res); }) .catch(function(err) { message.innerText=”Connection error ” + err; }) .then (function() { loading.style.display = ‘none’; }); });

The most interesting part, and important for this example, is in the call to the axios.get() method. As the first parameter we indicate the resource that we want to access (it will be a file called text.txt that will be found in the same folder as this example), followed by a configuration object. In that object we can send many things to configure the request, such as parameters, the response time before giving a timeout, credentials for authorization, the maximum response size allowed, the use of a proxy, etc. In our case we simply indicate that the expected response is of type text, with responseType: ‘text’.

The axios.get() method returns a promise. Therefore, below you will find the definition of the behaviors for the positive case and for the error case. The function defined as “then” receives a response object, in case everything went well. The function defined for the “catch” receives the error message, in case something has gone wrong. The last “then” you find after the “catch” is used to write code that will be executed in both the positive and negative cases.

Access to a resource from a REST API

Our second example illustrates how easy it is to make a request to a web service that returns data in JSON.

Note: we use JSON Placeholder as a fake REST API but you could perfectly use your own data set very easily with . var button = document.getElementById(‘json_get’); button.addEventListener(‘click’, function() { loading.style.display = ‘block’; axios.get(‘https://jsonplaceholder.typicode.com/todos/1’, { responseType: ‘json’ }) .then(function(res) { if(res.status==200) { console.log(res.data); message.innerHTML = res.data.title; } console.log(res); }) .catch( function(err) { console.log(err); }) .then(function() { loading.style.display = ‘none’; }); });

In this example the code is quite similar. You will only see that we are accessing a URL from a remote server that returns data in JSON format. Also, we inform Axios that the expected response is JSON (responseType: ‘json’). In the response object, in the “data” property you find the complete JSON returned by the server.

Example of a request to send data by POST method

This third example allows sending data to a REST API, for an information insertion. In this case we use the axios.post() method, to which we feed the URL of the resource and the data to be sent.

In this case, the API returns a status 201 if the data could have been inserted, in which case we show a message with the ID of the inserted resource, generated by the REST API server and returned as the body of the response.

var button = document.getElementById(‘json_post’); button.addEventListener(‘click’, function() { loading.style.display = ‘block’; axios.post(‘https://jsonplaceholder.typicode.com/posts’, { data: { userId: 1, title: ‘This is a new post’, body: ‘body of this post. I like the Axios library!!’ } }) .then(function(res) { if(res.status==201) { message.innerHTML = ‘ The new Post has been stored with id: ‘ + res.data.id; } }) .catch(function(err) { console.log(err); }) .then(function() { loading.style.display = ‘none’; }); });

It doesn’t differ much from what we’ve seen in previous examples, so I understand you won’t have too much trouble following the code. We only have to mention here one of the advantages of Axios with respect to the Fetch API, that you compose your set of data to send by post with a plain Javascript object, and you don’t have to work with it.

Full Axios usage code

The complete code of a page that performs the examples we have just seen can be found below.

< meta http-equiv="X-UA-Compatible" content="ie=edge"> Document

See also  10 Reasons to Use the Mozilla Firefox Browser
Loading Facebook Comments ...
Loading Disqus Comments ...