Axios is a popular Promised-based HTTP client for JavaScript which can be used in both browser and Node.js application for making HTTP requests.

By using Axios, You can easily send asynchronous HTTP requests to REST endpoints to exchange data. It works perfect in all modern browsers, including Internet Explore 8 and higher. Axios can also be used in advanced JavaScript frameworks like React, Vue.js, Angular, etc.

Here is the complete list of features that Axios supports:

  • Make XMLHttpRequests from the browser
  • Make HTTP requests from Node.js
  • Supports the Promise API
  • Intercept request and response
  • Transform request and response data
  • Cancel requests
  • Automatic transforms for JSON data
  • Client side support for protecting against XSRF

In this tutorial, you will learn how to add Axios to your Node.js project and send different HTTP requests. To demonstrate Axios' use in real-world scenario, we will use Reqres REST API for all our examples.

Installation

There are multiple options available to add Axios to your project. Depending on your package manager, you can either use npm:

$ npm install axios --save

or yarn:

$ yarn add axios

or bower:

$ bower install axios

or add directly to your web page using CDN:

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

Axios API

If you have already used jQuery for making asynchronous requests (the famous $.get() and $.post() methods), understanding Axios API is easier for you. Just create a new instance of Axios and then pass the relevant data to axios object to start an HTTP request:

const axios = require('axios');

// Send a GET request
axios({
  method: 'get',
  url: 'https://reqres.in/api/users',
  data: {
    name: 'Jane',
    country: 'Canada'
  }
});

But for convenience, Axios provides aliases for all supported HTTP request methods:

  • axios.get()
  • axios.post()
  • axios.put()
  • axios.patch()
  • axios.delete()
  • axios.options()
  • axios.head()

The response object returned by axios contains the following information:

{
  data: {}, // response that was provided by the server
  status: 200, //the HTTP status code from the server response
  statusText: 'OK', //the HTTP status message from the server response
  headers: {}, //the headers sent by the server (names are lowercased)
  config: {}, //the config that was provided to `axios` for the request
  request: {} //the request that generated this response
}

The response data is automatically converted to JSON object by axios so you do not need to parse it.

GET Request

Below Node.js example calls the REST web service to retrieve a list of users using axios.get() method, and then print them. We are using async/await syntax which is a part of ECMAScript 2017:

const axios = require('axios');

const listUsers = async () => {
    try {
        const res = await axios.get('https://reqres.in/api/users');
        console.log(res.data.data);
    } catch (err) {
        console.error(err);
    }
};

listUsers();

If you do not want to use async/await or want to use Axios in older browsers, you can use promises to communicate with the REST API:

const axios = require('axios');

axios.get('https://reqres.in/api/users')
    .then(res => {
        console.log(res.data.data);
    })
    .catch(err => {
        console.log(err);
    });

GET Request with Parameters

A GET request may contain query parameters in the URL. With Axios, you can either add parameters to URL like below:

axios.get('https://www.google.com/search?q=axios')

or use params property in the options:

axios.get('https://www.google.com/search', {
    params: {
        q: 'axios'
    }
})

POST Request

A POST request is used to create a new user. Axios provides axios.post() method to make an HTTP post request:

const axios = require('axios');

const createUser = async () => {
    try {
        const res = await axios.post('https://reqres.in/api/users', {
            name: 'Atta',
            job: 'Freelance Developer'
        });
        console.log(res.data);
    } catch (err) {
        console.error(err);
    }
};

createUser();

PUT Request

Using axios.put() function, we can update the user object:

const axios = require('axios');

const updateUser = async () => {
    try {
        const res = await axios.put('https://reqres.in/api/users/2', {
            name: 'Atta Shah',
            job: 'MEAN Stack Developer'
        });
        console.log(res.data);
    } catch (err) {
        console.error(err);
    }
};

updateUser();

DELETE Request

If you want to delete an object from server using REST API with Axios, use axios.delete() method:

const axios = require('axios');

const deleteUser = async () => {
    try {
        const res = await axios.delete('https://reqres.in/api/users/2');
        console.log(res.status);
    } catch (err) {
        console.error(err);
    }
};

deleteUser();

Concurrent Requests

Another benefit of using Axios is that you can send multiple HTTP requests simultaneously using axios.all()method:

const axios = require('axios');

const loadUsers = async () => {
    try {
        const [res1, res2] = await axios.all([
            axios.get('https://reqres.in/api/users/1'),
            axios.get('https://reqres.in/api/users/2')
        ]);
        console.log(res1.data);
        console.log(res2.data);
    } catch (err) {
        console.error(err);
    }
};

loadUsers();

To learn about more Node.js HTTP clients, checkout 7 Ways to Make HTTP Requests in Node.js tutorial.

Summary

Axios is a Promise-based HTTP client library for the browser and Node.js. It can be used together with more advanced front-end frameworks like React or Vue.js as well as in your Node.js backend application.

  • Axios provides HTTP request methods for all HTTP verbs e.g. axios.get(), axios.post(), axios.put() etc.
  • Axios supports both async/await and Promises.
  • Axios automatically transforms the server response to a JSON object. So there is no need to use JSON.parse().
  • Axios provides axios.all() function for sending multiple requests simultaneously.

For more configuration options, check out Axios docs on GitHub. If you want to use Axios in the browser, check out my Axios in JavaScript guide.

Like this article? Follow @attacomsian on Twitter. You can also follow me on LinkedIn and DEV.


Need help to start a new Spring Boot or MEAN stack project? I am available for contract work. Hire me to accomplish your business goals with engineering and design. Let’s talk about your project: hi@attacomsian.com.