Difference between revisions of "HTTP Client for Javascript Using Axios Library"

From WikiHTP
(Access to a REST API resource)
(Example of Ajax access to recover a plain text)
 
Line 98: Line 98:
 
     .then(function(res) {
 
     .then(function(res) {
 
       if(res.status==200) {
 
       if(res.status==200) {
         mensaje.innerHTML = res.data;
+
         message.innerHTML = res.data;
 
       }
 
       }
 
       console.log(res);
 
       console.log(res);
 
     })
 
     })
 
     .catch(function(err) {
 
     .catch(function(err) {
       mensaje.innerText = 'Connection error ' + err;
+
       message.innerText = 'Connection error ' + err;
 
     })
 
     })
 
     .then(function() {
 
     .then(function() {

Latest revision as of 01:09, 30 May 2019

Meet the Axios library, a simple compliment to make HTTP requests (Ajax) through Javascript / NodeJS, highly prepared to consume REST APIs. If you want to do Ajax in Javascript, Axios can be a great ally. It is a Javascript library capable of running both in the browser and in NodeJS, which facilitates all types of operations as an HTTP client.

With Axios, you can make requests against a server, completely configurable, and receive the answer 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 can observe its operation.

The library is based on promises, so by using it, we can generate a fairly ordered 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 be compatible with browsers.

Why Axios[edit]

Axios can be useful in many situations, although it will not always be so necessary. It would be necessary to analyze carefully in which frame we are to see if Axios is or not our best solution. Here we leave you some considerations.

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

Many people use jQuery to be able to use Ajax-related methods, but the truth is that using jQuery only for this reason is not very advisable, since it is a rather heavy library, compared to Axios.

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

Axios is an alternative that offers us several advantages:

  • It offers a unified API for Ajax applications.
  • It is highly thought to facilitate the consumption of web services, REST API that returns JSON data.
  • It is very simple to use and can be an ideal complement for conventional web sites, where jQuery is not being used and modern frontend applications based on libraries like React or Polymer, which do not have in their "core" mechanisms to make 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 we will save a lot of coding work in the applications.


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

Use Axios[edit]

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

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

Install Axios[edit]

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

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

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

npm install axios

Once installed in the browser, we have an object called "axios", which has a method API to perform common HTTP operations, GET, POST ...

Note: if you use it within 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[edit]

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

We are going to see several examples of Axios use thought for the browser. In general, we will make the Ajax request and implement the typical behaviour:

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

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

<button id="load_ajax">Load content</button> 
<button id="json_get">Request JSON GET</button> 
<button id="json_post">Request JSON POST</button>
<div id="message"></div>
<div id="loading"> loading...</div>

The message "loading" is initially hidden thanks to this CSS:

<style>
  #loading {
    display: none;
  }
</style>

At the end of the article you have the complete example of the code, in case of doubts arise.

Example of Ajax access to recover a plain text[edit]

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

var loading = document.getElementById('loading');
var message = document.getElementById('message');

var boton = document.getElementById('load_ajax');
boton.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 a first parameter, we indicate the resource that we want to access (it will be a file called text.txt that will be in the same folder of this example), followed by a configuration object. In this object, we can send many things to configure the request, such as parameters, the response time before giving a timeout, credentials for authorization, the size of the maximum response allowed, the use of a proxy, etc. In our case, we simply tell you that the expected response is text type, with responseType: 'text'.

The axios.get () method returns a promise. Therefore, below you find the definition of the behaviours for the positive case and for the case of error. 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 failed. The last "then" that you find behind the "catch" is used to write code that will be executed both in the positive case and the negative case.

Access to a REST API resource[edit]

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

Note: we use JSON Placeholder as API REST fake but you could perfectly use your own data set very easily with REST API fake JSON-Server.

var boton = document.getElementById('json_get');
boton.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. In addition, 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[edit]

This third example allows to send data to a REST API, for insertion of information. In this case, we use the axios .post () method, which we feed with the URL of the resource and the data that we want to send.

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

var boton = document.getElementById('json_post');
boton.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 bookshop!!'
    }
  })
    .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 does not differ much from what we have seen in previous examples, so I understand that you will not have too many problems to follow the code. We only have to mention here one of the advantages of Axios with respect to the Fetch API, that your data set to send by post is compiled with a flat Javascript object, and you do not need to work with the FormData API to compose the data in the appropriate format for the POST request.

Complete code of use of Axios[edit]

The complete code of a page that makes the examples that we have just seen you find below.

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <meta http-equiv="X-UA-Compatible" content="ie=edge">
  <title>Document</title>
  <style>
  #loading {
    display: none;
  }
  </style>
  <script src="node_modules/axios/dist/axios.min.js"></script>
</head>
<body>
  
  <button id="load_ajax">Load content</button> 
  <button id="json_get">Request JSON GET</button> 
  <button id="json_post">Request JSON POST</button>
  <div id="message"></div>
  <div id="loading"> loading...</div>
  
  <script>
var loading = document.getElementById('loading');
var message = document.getElementById('message');

var boton = document.getElementById('load_ajax');
boton.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';
    });
});


    var boton = document.getElementById('json_get');
    boton.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';
        });
    });

    var boton = document.getElementById('json_post');
    boton.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 bookstore!'
        }
      })
        .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';
        });
    });
  </script>
</body>
</html>

Conclusion[edit]

Axios is a good alternative to consider especially in applications or components where you require access to resources of a REST API. With a weight of the library more than adjusted, we think it is worth using it if we do not have another available HTTP client in our application.

It adds a lot of value thanks to a huge amount of options for configuring the requests, which will make it very easy for you to attend the demands of the API with which you are connecting. It also receives the answers in a way that is also easy to process. It is a good alternative to the Fetch + polyfills API because it is easier to use.

You can find information on all possible options on the Axios project page on Github.