ZetCode

Axios tutorial

last modified February 10, 2021

Axios tutorial shows how to generage requests in JavaScript using Axios client library. Check the JavaScript fetch tutorial for an alternative way of creating requests in JavaScript.

Axios

Axios is a promise based HTTP client for the browser and Node.js. Axios makes it easy to send asynchronous HTTP requests to REST endpoints and perform CRUD operations. It can be used in plain JavaScript or with a library such as Vue or React.

In this tutorial we work with Axios in a Node.js application.

Setting up Axios

First, we install Axios.

$ node -v
v12.20.1

We use Node.js version 12.20.1.

$ npm init -y

We initiate a new Node.js application.

$ npm i axios

We install Axios with npm i axios command.

Axios making requests

There are multiple methods for creating requests in axios.

axios(config) 
axios(url[, config])

These are basic methods for generating requests in axios.

axios.request(config)
axios.get(url[, config])
axios.delete(url[, config])
axios.head(url[, config])
axios.options(url[, config])
axios.post(url[, data[, config]])
axios.put(url[, data[, config]])
axios.patch(url[, data[, config]])

These are method aliases, created for convenience.

Axios Response object

When we send a request to a server, it returns a response. The Axios response object consists of:

Axios GET request with callbacks

In the first example, we create a simple GET request. We use callbacks.

get_req.js
const axios = require('axios');

axios.get('http://webcode.me').then(resp => {

    console.log(resp.data);
});

We generate a simple GET request and show the output.

const axios = require('axios');

The Axios library is included.

axios.get('http://webcode.me').then(resp => {

    console.log(resp.data);
});

With get, we send a GET request. We output the data from the response. The data is HTML code.

$ node get_req.js
<!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>My html page</title>
</head>
<body>

    <p>
        Today is a beautiful day. We go swimming and fishing.
    </p>

    <p>
          Hello there. How are you?
    </p>

</body>
</html>

Axios GET request with async/await

The following example creates the same request. This time we use async/await syntax.

get_req_async.js
const axios = require('axios');

async function makeGetRequest() {

  let res = await axios.get('http://webcode.me');

  let data = res.data;
  console.log(data);
}

makeGetRequest();

The example creates a simple GET request utilizing async/await syntax.

Axios basic API

The get, post, or delete methods are convenience methods for the basic axios API: axios(config) and axios(url, config).

basic_api.js
const axios = require('axios');

async function makeRequest() {

    const config = {
        method: 'get',
        url: 'http://webcode.me'
    }

    let res = await axios(config)

    console.log(res.status);
}

makeRequest();

The example creates a GET request to webcode.me.

const config = {
    method: 'get',
    url: 'http://webcode.me'
}

We specify the details of the request in the configuration object.

Axios HEAD request

A HEAD request is a GET request without a message body. In Axios, a HEAD request is created with head.

head_req.js
const axios = require('axios');

async function makeHeadRequest() {

  let res = await axios.head('http://webcode.me');

  console.log(`Status: ${res.status}`)
  console.log(`Server: ${res.headers.server}`)
  console.log(`Date: ${res.headers.date}`)
}

makeHeadRequest();

The example shows the status, server name, response date from a response generated with a HEAD request.

$ node head_req.js 
Status: 200
Server: nginx/1.6.2
Date: Wed, 10 Feb 2021 09:52:59 GMT

Axios status code

HTTP response status codes indicate whether a specific HTTP request has been successfully completed. Responses are grouped in five classes:

status_code.js
const axios = require('axios');

async function makeRequest() {

    const config = {
        method: 'head',
        url: 'http://webcode.me'
    }

    let res = await axios(config)

    console.log(res.status);
}

makeRequest();

We get the status code from the status property of the response.

$ node status_code.js 
200

Axios custom header

In the following example, we send a custom header.

custom_header.js
const axios = require('axios');

async function makeRequest() {

    const config = {
        method: 'get',
        url: 'http://webcode.me',
        headers: { 'User-Agent': 'Axios - console app' }
    }

    let res = await axios(config)

    console.log(res.request._header);
}

makeRequest();

The example sends a customized header.

const config = {
    method: 'get',
    url: 'http://webcode.me',
    headers: { 'User-Agent': 'Axios- console app' }
}

The custom data is added to the headers attribute of the configuration object.

console.log(res.request._header);

We verify the sent data.

$ node custom_header.js
GET / HTTP/1.1
Accept: application/json, text/plain, */*
User-Agent: Console app
Host: webcode.me
Connection: close

Axios GET request query parameters

In the following example, we append some query parameters to the URL.

get_req_query.js
const axios = require('axios');
const url = require('url');

async function makeGetRequest() {

    let payload = { name: 'John Doe', occupation: 'gardener' };

    const params = new url.URLSearchParams(payload);

    let res = await axios.get(`http://httpbin.org/get?${params}`);

    let data = res.data;
    console.log(data);
}

makeGetRequest();

We use the URLSearchParams of the url module to transform the JSON object into suitable URL query form.

$ node get_req_query.js 
{
  args: { name: 'John Doe', occupation: 'gardener' },
  headers: {
    Accept: 'application/json, text/plain, */*',
    Host: 'httpbin.org',
    'User-Agent': 'axios/0.21.1',
    'X-Amzn-Trace-Id': 'Root=1-6023ba22-48b1ff807ea9d934457abbcd'
  },
  ...
  url: 'http://httpbin.org/get?name=John+Doe&occupation=gardener'
}

Getting Github information

Many online services contain public APIs. In the following example, we generate a request to a Github API.

github_info.js
const axios = require('axios');

async function getNumberOfFollowers() {

  let res = await axios.get('https://api.github.com/users/janbodnar');

  let nOfFollowers = res.data.followers;
  let location = res.data.location;

  console.log(`# of followers: ${nOfFollowers}`)
  console.log(`Location: ${location}`)
}

getNumberOfFollowers();

In the example, we get the number of followers and location of a user.

$ node github_info.js 
# of followers: 195
Location: Bratislava

Axios POST JSON request

A POST request is created with post method.

Axios automatically serializes JavaScript objects to JSON when passed to the post function as the second parameter; we do not need to serialize POST bodies to JSON.

post_json.js
const axios = require('axios');

async function makeGetRequest() {

    let payload = { name: 'John Doe', occupation: 'gardener' };

    let res = await axios.post('http://httpbin.org/post', payload);

    let data = res.data;
    console.log(data);
}

makeGetRequest();

The example creates a POST request to an online testing service. The payload is the second parameter to the post function.

$ node post_json.js 
{
  args: {},
  data: '{"name":"John Doe","occupation":"gardener"}',
  files: {},
  form: {},
  headers: {
    Accept: 'application/json, text/plain, */*',
    'Content-Length': '43',
    'Content-Type': 'application/json;charset=utf-8',
    Host: 'httpbin.org',
    'User-Agent': 'axios/0.21.1',
    'X-Amzn-Trace-Id': 'Root=1-6023bc92-5bcf8f4e10f829be3a3f04f7'
  },
  json: { name: 'John Doe', occupation: 'gardener' },
  ...
  url: 'http://httpbin.org/post'
}

Axios POST FORM request

In the following example, we generate a POST request with form data.

$ npm i form-data

We install the form-data module.

With application/x-www-form-urlencoded the data is sent in the body of the request; the keys and values are encoded in key-value tuples separated by '&', with a '=' between the key and the value.

post_form.js
const axios = require('axios');
const FormData = require('form-data');

async function makeGetRequest() {

    const form_data = new FormData();
    form_data.append('name', 'John Doe');
    form_data.append('occupation', 'gardener');

    let res = await axios.post('http://httpbin.org/post', form_data, 
        { headers: form_data.getHeaders() });

    let data = res.data;
    console.log(data);
}

makeGetRequest();

To produce form data in the appropriate format, we use the FormData object.

$ node post_form.js 
{
  args: {},
  data: '',
  files: {},
  form: { name: 'John Doe', occupation: 'gardener' },
  headers: {
    Accept: 'application/json, text/plain, */*',
    'Content-Length': '284',
    'Content-Type': 'multipart/form-data; ...
    Host: 'httpbin.org',
    'User-Agent': 'axios/0.21.1',
    'X-Amzn-Trace-Id': 'Root=1-6023bff5-056fc9fd39f94e870b52169b'
  },
  json: null,
  ...
  url: 'http://httpbin.org/post'
}

Axios download image

The following example shows how to download an image with Axios.

get_image.js
const axios = require('axios');
const fs = require('fs');

var config = {
    responseType: 'stream'
};

let url = 'https://images.dog.ceo/breeds/setter-english/n02100735_4870.jpg';

async function getImage() {

    let resp = await axios.get(url, config);
    resp.data.pipe(fs.createWriteStream('image.jpg'));
}

getImage();

The example retrieves an image from an online service, which keeps images of dogs.

const axios = require('axios');
const fs = require('fs');

We include axios and fs modules.

var config = {
    responseType: 'stream'
};

We specify the response type in the configuration object.

let resp = await axios.get(url, config);

We get the image.

resp.data.pipe(fs.createWriteStream('image.jpg'));

With the help of the fs module, we save the image to disk.

Axios multiple requests

We can create multiple requests in one shot with Axios.

multiple_requests.js
const axios = require('axios');

async function makeRequests() {

    let [u1, u2] = await Promise.all([
        axios.get('https://api.github.com/users/janbodnar'),
        axios.get('https://api.github.com/users/symfony')
    ]);

    console.log(`Jan Bodnar: ${u1.data.created_at}`);
    console.log(`Symfony: ${u2.data.created_at}`);
}

makeRequests();

To send multiple requests, we use the Promise.all() method.

$ node multiple_requests.js
Jan Bodnar: 2016-01-31T12:12:28Z
Symfony: 2009-10-24T04:05:23Z

Using Axios with JSON Server

JSON Server is a wonderful tool, which allows us to create fake REST APIs easily.

$ npm i -g json-server

We install json-server.

users.json
{
  "users": [
    {
      "id": 1,
      "first_name": "Robert",
      "last_name": "Schwartz",
      "email": "rob23@gmail.com"
    },
    {
      "id": 2,
      "first_name": "Lucy",
      "last_name": "Ballmer",
      "email": "lucyb56@gmail.com"
    },
    {
      "id": 3,
      "first_name": "Anna",
      "last_name": "Smith",
      "email": "annasmith23@gmail.com"
    },
    {
      "id": 4,
      "first_name": "Robert",
      "last_name": "Brown",
      "email": "bobbrown432@yahoo.com"
    },
    {
      "id": 5,
      "first_name": "Roger",
      "last_name": "Bacon",
      "email": "rogerbacon12@yahoo.com"
    }
  ]
}

This is our test data.

Starting JSON server

The JSON server is started with the json-server, which we have installed globally.

$ json-server --watch users.json    

The --watch option is used to specify the data for the server.

$ curl localhost:3000/users/2/
{
  "id": 2,
  "first_name": "Lucy",
  "last_name": "Ballmer",
  "email": "lucyb56@gmail.com"
}

With the curl command, we get the user with Id 2.

Posting a user

We post a new user.

post_user.js
const axios = require('axios');

async function makePostRequest() {

    params = {
        id: 6,
        first_name: 'Fred',
        last_name: 'Blair',
        email: 'freddyb34@gmail.com'
      }

    let res = await axios.post('http://localhost:3000/users/', params);

    console.log(res.data);
}

makePostRequest();

The example posts a new user.

let res = await axios.post('http://localhost:3000/users/', params);

The post parameters are passed as the second parameter to the post() method.

Getting users

We get users from the test server.

get_users.js
const axios = require('axios');

async function makeGetRequest() {

  let res = await axios.get('http://localhost:3000/users/');

  let data = res.data;
  console.log(data);
}

makeGetRequest();

This program retrieves all users from our test server.

$ node get_users.js
[ { id: 1,
    first_name: 'Robert',
    last_name: 'Schwartz',
    email: 'rob23@gmail.com' },
  { id: 2,
    first_name: 'Lucy',
    last_name: 'Ballmer',
    email: 'lucyb56@gmail.com' },
  { id: 3,
    first_name: 'Anna',
    last_name: 'Smith',
    email: 'annasmith23@gmail.com' },
  { id: 4,
    first_name: 'Robert',
    last_name: 'Brown',
    email: 'bobbrown432@yahoo.com' },
  { id: 5,
    first_name: 'Roger',
    last_name: 'Bacon',
    email: 'rogerbacon12@yahoo.com' },
  { id: 6,
    first_name: 'Fred',
    last_name: 'Blair',
    email: 'freddyb34@gmail.com' } ]

Deleting a user

A resource is deleted with delete.

delete_user.js
const axios = require('axios');

async function makePostRequest() {

    let res = await axios.delete('http://localhost:3000/users/2/');

    console.log(res.status);
}

makePostRequest();

The example deletes the user with Id 2.

In this tutorial, we have worked with JavaScript Axios module.

List all JavaScript tutorials.