Open In App

How To Use Axios NPM to Generate HTTP Requests ?

In this article, we are going to learn about Axios and HTTP requests and using Axios to generate HTTP requests. Axios is a promise-based HTTP library that is used by developers to make requests to their APIs or third-party API endpoints to fetch data. It is a popular JavaScript library used for making HTTP requests from web browsers and NodeJS applications. It provides a simple and intuitive API for performing asynchronous operations like fetching data from APIs, posting form data, and more.

HTTP Requests:

HTTP (Hypertext Transfer Protocol) requests are a medium that enables clients such as browsers of web applications to communicate with servers to retrieve or send data over the internet. They consist of a request method (such as GET, POST, PUT, DELETE), a URL specifying the resource, headers containing additional information, and a request body carrying data (optional). The server then processes the request and returns a response, typically including a status code indicating the outcome (success or failure) along with any requested data as response or error messages

Axios:

Axios is a popular JavaScript library that allows users to make HTTP requests to a RESTful or GraphQL API. It performs similar tasks to fetch API provided by browsers. Axios makes use of promises to fulfill the request. Axios is better than Fetch API because of the following reasons:

How does Axios work?

Axios operates by initiating HTTP requests in NodeJS and utilizing XMLHttpRequests in the browser. Upon successful request, a response containing the requested data is received. Conversely, in case of failure, an error is returned. Additionally, Axios enables interception of requests and responses, facilitating their transformation or modification.

Installing Axios NPM for Your Project:

There are several ways to incorporate Axios into your project.

You can use npm:

$ npm install axios

Or yarn:

$ yarn add axios

Or add to your web page using CDN:

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

Or

<script src=”https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js”></script>

Creating an Axios Instance With Default Settings:

If one wants to create an axios instance with default settings, axios.create() method can be used. It allows you to create a new instance of Axios with default configuration options. It can be done like this.

We can look at this in a more simple way as well, as for convenience we generally directly user axios.get() and axios.post() etc.

const axios = require('axios');

// create an instance with default settings
const instance = axios.create({
    baseURL: 'https://api.endpoint.com',
    timeout: 10000, // timeout for requests can be set
    headers: {
        'Content-Type': 'application/json',
    },
    // other default settings can be added
});

// use the instance to make http requests
instance.get('/endpoint')
    .then(respons => {
        console.log('Response:', response.date);
    })
    .catch(error => {
        console.error('Error:', error);
    });

Performing GET Requests With Axios:

In the following example, a GET request is being made to a specified api endpoint:

const getData = async () => {
    try {
        return await axios.get("endpoint")
    } catch (error) {
        console.error();
    }
}

getData();

Performing POST Requests With Axios:

We just need to customize the config object passed to the axios function for every type of HTTP request we want to make. POST request can be made using Axios to post data to a given endpoint and trigger events. To perform an HTTP request in Axios, we call axios.post().

Requirements:

axios.post('/endpoint', { your_request_object })
    .then((response) => {
        console.log(response);
    }, (error) => {
        console.log(error);
    });
axios({
    method: 'post',
    url: '/endpoint',
    data: {
        //...your response object
    }
});

Sending Data with POST Requests:

Here we make use of async and await syntax which are methods under Promises API. They help in writing cleaner and manageable code that is easier to interpret and gives a synchronous feel. Any request object can be sent in the similar fashion and this is how axios is incorporated into the code using a wrapper function.

Let's take an example of a login request where we are sending username and example as the request object:

const loginData = async (credentials) => {
    try {
        const response = await axios.post(url, credentials)
        console.log(response.data);
    } catch (error) {
        console.log(error);
    }
};

loginData({
    username: "Finn",
    password: "fin237r87@#"
});

Handling Response Data From POST Requests:

Now let's take the above example for understanding our response. Once an HTTP POST request is made, Axios returns a promise that is either fulfilled or rejected, depending on the response from the backend service.

axios.post('/login', credentials)
    .then((response) => {
        console.log(response);
    }, (error) => {
        console.log(error);
    });
{
// `data` is the response sent by the server
data: {},

// `status` is the HTTP status code from the server response
status: 200,

// `statusText` is the HTTP status message from the server response
statusText: 'OK',

// `headers` the headers that the server responded with
// All header names are lower cased
headers: {},

// `config` is the config that was provided to `axios` for the request
config: {},

// `request` is the request that generated this response
// It is the last ClientRequest instance in node.js (in redirects)
// and an XMLHttpRequest instance the browser
request: {}
}
const options = {
    method: 'post',
    url: '/login',
    data: credentials,
    transformRequest: [(data, headers) => {
        // transform the data

        return data;
    }]
};

// send the request
axios(options);

Shorthand Methods for Axios HTTP Requests:

Axios provides various shorthand methods for performing different types of requests. They are as follows:

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]])

Error Handling With Axios:

An HTTP request can succeed or fail. Errors can occur and it is the developer's responsibility to handle the errors for a better user experience. Errors can occur due to a variety of reasons like server errors, authentication errors, missing parameters and requesting resources that may not exist. Axios, by default, rejects any response with a status code that falls outside the successful 2xx range. But this feature can be modified to specify what range of HTTP codes should throw an error using the validateStatus config option. Following is an example depicting this:

axios({
    baseURL: "endpoint",
    url: "/todos/1",
    method: "get",
    validateStatus: status => status <= 500,
})
    .then((response) => {
        console.log(response.data);
    })
    .catch(error => {
        console.log(error)
    })

the error object that Axios passes to the .catch block has several properties like name, message, code, status, stack and config and can be accessed like this: error.name. In addition these properties, if the request was made and the server responded with a status code that falls outside the 2xx range, the error object will also have the error.response object. On the other hand, if the request was made but no response was received, the error object will have an error.request object.

axios.post("/login", credentials)
    .then(response => {
        console.log(response);
    })
    .catch(error => {
        if (error.response) {
            //response status is an error code
            console.log(error.response.status);
        }
        else if (error.request) {
            //response not received though the request was sent
            console.log(error.request);
        }
        else {
            //an error occurred when setting up the request
            console.log(error.message);
        }
    })

Conclusion:

The only reason axios is so popular among developers is because of useful and simple to understand features. It has a number of configurations that allow us to change the default behavior to suit our needs. This article depicts how seamlessly one can use axios to connect their client side service to backend service or any other API.

Article Tags :