Ebooks

Axios tutorial

Axios tutorial shows how to generage requests in JavaScript using Axios client library.

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
v11.5.0

We use Node.js version 11.5.

$ npm init -y

We initiate a new Node.js application.

$ npm i axios

We install Axios with npm i axios command.

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.

simple_get.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 simple_get.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>

This is the output.

Axios GET request with async/await

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

simple_get.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 HEAD request

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

head_request.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_request.js
Status: 200
Server: nginx/1.6.2
Date: Mon, 04 Feb 2019 15:08:56 GMT

This is the output.

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 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': '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': '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

This is the output.

Getting Github information

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

github.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.js
# of followers: 44
Location: Bratislava

This is the output.

Axios POST request

A POST request is created with post() method.

post_request.php
const axios = require('axios');

async function makePostRequest() {

    let res = await axios.post('https://jsonplaceholder.typicode.com/posts');

    console.log(`Status code: ${res.status}`);
    console.log(`Status text: ${res.statusText}`);
    console.log(`Request method: ${res.request.method}`);
    console.log(`Path: ${res.request.path}`);

    console.log(`Date: ${res.headers.date}`);
    console.log(`Data: ${res.data}`);
}

makePostRequest();

The example creates a POST request to an online testing service.

$ node post_request.js
Status code: 201
Status text: Created
Request method: POST
Path: /posts
Date: Mon, 04 Feb 2019 16:54:36 GMT
Data: [object Object]

This is the output.

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

This is the output.

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 data.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' } ]

This is the output.

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.

You might also be interested in the following related tutorials: JSON Server tutorial, Jest tutorial, Moment.js tutorial, Reading JSON from URL in JavaScript, JavaScript Snake tutorial, JQuery tutorial, Node Sass tutorial, Lodash tutorial.