Open In App

How To Use Axios NPM to Generate HTTP Requests ?

Last Updated : 04 Apr, 2024
Improve
Improve
Like Article
Like
Save
Share
Report

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:

  • Request and response interception
  • Protection again SXRF
  • Support for older browsers
  • Support for upload progress
  • Works with Node.js
  • Request Cancellation
  • Setting up Response timeout
  • Streamlined error handling
  • Automatic JSON data transformation

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.

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

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

  • URL of the service endpoint
  • object that contains the properties you wish to send to the server
JavaScript
axios.post('/endpoint', { your_request_object })
    .then((response) => {
        console.log(response);
    }, (error) => {
        console.log(error);
    });
  • The request can also be frame in such a way:
JavaScript
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:

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

  • To handle the response, we can use then() method:
JavaScript
axios.post('/login', credentials)
    .then((response) => {
        console.log(response);
    }, (error) => {
        console.log(error);
    });
  • If the promise is fulfilled, the first argument of then() will be called; if the promise is rejected, the second argument will be called. We can also follow a try-catch block format.
{
// `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: {}
}
  • Axios automatically converts request and response to JSON by default, but it can also you to override the default behavior and define a different transformation mechanism. Some APIs accept formats such as XML or CSV and this feature can be very useful for that.
  • To change request data before sending it to the server, set the transformRequest property in the config object. Note that this method only works for PUT, POST, DELETE, and PATCH request methods.
JavaScript
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:

  • Make a custom HTTP request using the provided config
axios.request(config)
  • GET requests are used to retrieve data from the server
axios.get(url[, config])
  • DELETE requests are used to delete a resource from the server
axios.delete(url[, config])
  • Similar to GET, but retrieve headers of the response
axios.head(url[, config])
  • Used to determine the communication options available for a given resource
axios.options(url[, config])
  • Used to submit data to the server to create or update a resource
axios.post(url[, data[, config]])
  • Used to update an existing resource
axios.put(url[, data[, config]])
  • Used to apply partial modifications to a resource
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:

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

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



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads