How to make HTTP Requests Using Axios Library

HTTP Requests Using Axios Library
Reading Time: 3 minutes

Introduction

Axios is a Javascript library used to perform HTTP requests for Nodejs and browsers. It supports the Promise API and makes it easy to send requests asynchronously. In this article, we will learn, how to make GET/POST/PUT/DELETE HTTP requests using Axios.

Features

  • 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

Installation

We can install Axios in our project in one of the following ways:

npm command:

$ npm install axios

yarn command:

$ yarn add axios

using CDN:

https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js

In this article, we will use the npm command to install the Axios. For that, we need to require the Axios in the project

Making Request using Axios

Syntax of Axios is given below.

Syntax : axios(config)

Now, in the given syntax what does this config consist of? To make the request we have to pass the relevant config to Axios. Only the URL is required and if we do not specify the method, it is by default considered as GET request. Request config consists of:

axios({
    method:'method',
    url: 'url',
    baseURL: 'https://axios/api/',
    headers: {'X-Requested-With': 'XMLHttpRequest'},
    data: {},
    responseType: 'json',   
}) 

There are many more available config requests. For more information please visit: https://www.npmjs.com/package//axios#request-config

Axios also provides a set of shorthand methods for performing different types of requests. The methods are as follows:

  • axios.request(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]])

Axios Responce Object

When a request is sent to the server, it returns a response that contains an object having information as given below:

  • data – the payload returned from the server
  • status – the HTTP code returned from the server
  • statusText – the HTTP status message returned by the server
  • headers – headers sent by the server
  • config – the original request configuration
  • request – the request object

For example:

const axios  = require("axios");

function example(){
    axios({
        method :'get',
        url : 'http://127.0.0.1:5500/data.json'
    }).then(res=> {
        console.log(res);
    })
}
example();

As a result, we will get:

Axios GET Request

To understand the get request, let’s assume that we have JSON data in data.json file same as shown below which we want to get and we have a main index.js file:

data.json file:

{
    "id": 1,
    "name": "Marry ",
    "designation": "Software Consultant"
    
}

index.js file:

const axios  = require("axios");

function getFunction() {
    config = {
        method: 'get',
        url: 'http://127.0.0.1:5500/data.json'
    }

    axios(config)
        .then(res => {
            console.log(res.data);
        })
        .catch(error => console.log(error));
}
getFunction();

or we can write the same code as:

const axios  = require("axios");

function getFunction() {
    axios.get('http://127.0.0.1:5500/data.json')
        .then(res => {
            console.log(res.data);
        })
        .catch(error => console.log(error));
}
getFunction();

The above examples are using callbacks. Let’s understand how to write get request using async/await. An example is shown in the below image:

const axios  = require("axios");

async function getFunction() {
    try {
        const res = await axios.get('http://127.0.0.1:5500/data.json');
        console.log(res.data);
    } catch (error) {
        console.log(error)
    }
}
getFunction();

Axios POST Request

Below is the example of a POST request using callbacks:

const axios = require("axios");

function postFunction() {
    const config = {
        method: 'POST',
        headers: {'Content-Type': 'application/json'},
        data : { id: 2, name: 'Christina', designation: 'Software Consultant' }
    };

    axios.post('/data', config)
    .then((res) => {
        console.log(res.data);
    })
    .catch(error => console.log(error));
}

postFunction();

using Async/await:

const axios = require("axios");

async function postFunction() {
    try{
        const config = {
            method: 'POST',
            headers: {'Content-Type': 'application/json'},
            data : { id: 2, name: 'Christina', designation: 'Software Consultant' }
        };
        let res = await axios.post('/data', config);
        console.log(res.data);
    } catch (error) {
        console.log(error)
    }
}

postFunction();

Axios PUT Request

Below is an example of a PUT request using callbacks. In this example, we are updating the data where id = 1.

const axios = require("axios");

function putFunction() {
    const config = {
        method: 'PUT',
        headers: {'Content-Type': 'application/json'},
        data : { id: 1, name: 'Marry', designation: 'Sr. Software Consultant' }
    };

    axios.put('/data/1', config)
    .then((res) => {
        console.log(res.data);
    })
    .catch(error => console.log(error));
}

putFunction();

using async/await:

const axios = require("axios");

async function putFunction() {
    try{
        const config = {
            method: 'PUT',
            headers: {'Content-Type': 'application/json'},
            data : { id: 1, name: 'Marry', designation: 'Sr. Software Consultant' }
        };
        let res = await axios.put('/data/1', config);
        console.log(res.data);
    } catch (error) {
        console.log(error)
    }
}

putFunction();

Axios Delete Request

An example is given below to delete specific data and as a result, it will delete the data having id =1.

const axios = require("axios");

function deleteFunction() {
    axios.delete('/data/1', config)
    .then((res) => {
        console.log(res.data);
    })
    .catch(error => console.log(error));
}

deleteFunction();

Conclusion

So with this blog, hope I was able to explain how we can make basic HTTP requests ( get, post, put and delete ) using Axios. Thank you for reading and if you really like the blog hit the like button, and to learn more, Visit here

Discover more from Knoldus Blogs

Subscribe now to keep reading and get access to the full archive.

Continue reading