Share


Axios Tutorial


By gobrain

Jun 19th, 2024

As a JavaScript developer, a common task while developing any applications is interacting with REST APIs through HTTP requests. This is where Axios comes in.

In this article, we will explore what Axios is, how to install it, and various techniques for making HTTP requests with it. Let's get started.

What is Axios Used For?

Axios is a HTTP client API – set of methods and tools – used in the browser and Nodejs enviroments to make HTTP requests (GET, POST, DELETE, PUT and more) to backend services over the HTTP protocol.

Axios is based on the XMLHttpRequest object in browsers and the http module in Nodejs. This is why it can be used in both on the server side and on the client side.

Several advantages that Axios offers for making HTTP requests include:

  • Ease of Use: Axios provides a simple and consistent API for making HTTP requests
  • Promises: Axios uses Promises, which makes handling asynchronous operations more straightforward and helps prevent callback hell.
  • Error Handling: It includes robust error handling features
  • Request and Response Interceptions: Axios allows you to intercept requests and responses, enabling you to modify or handle them as needed.
  • Client-side Protection: Axios includes built-in protection against Cross-Site Request Forgery (XSRF) attacks.

Due to its these powerful features, Axios is so popular among developers. Axios has almost 101k starts on Github and 49m weekly downloads on NPM.

Now, let’s see how to install and use it in your javascript projects.

How To Install Axios

To use Axios, you first need to install it. You can add Axios to your project using different methods:

Using npm or yarn

To install Axios, you can use a package manager like npm (Node Package Manager) or yarn (an alternative package manager for Nodejs).

npm install axios
yarn add axios

Using CDNs

If you prefer not to use a package manager like npm, yarn, you can still use Axios in your web projects by including it via a Content Delivery Network (CDN)

CDNs provide direct links to libraries hosted on external servers, allowing you to include them in your HTML files without needing to install or manage them locally.

// Add your HTML file
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>

Once installed, you can import Axios into your JavaScript project.

import axios from 'axios'; // Frontend Libraries
const axios = require('axios') // Nodejs

Now, you are ready to make HTTP requests with Axios.

How Do You Make HTTP Requests with Axios?

Axios supports all major HTTP methods like GET, POST, PUT, DELETE and more. It provides a set of shorthand methods that make it easier to perform these HTTP requests.

For example, you can use axios.get for GET requests, axios.put for PUT requests, and so on. Popular other ones include:

  • axios.get(url[, config])
  • axios.post(url[, data[, config]])
  • axios.put(url[, data[, config]])
  • axios.patch(url[, data[, config]])
  • axios.delete(url[, config])

Now, let’s cover each with examples.

Get Request

A GET request is the fundamental request used to retrieve a document or data source from a target. To send a GET request in Axios, the axios.get() method is called. This method accepts an endpoint as an argument where the desired data is provided over it.

axios.get('https://api.example.com/posts')
  .then(response => {
    console.log(response.data); // The response body

  })
  .catch(error => {
    console.error(error);
  });

In this example, we make an HTTP Get request to an API to fetch all posts. When server respond our request, we simply log all posts to the console. Whenever an error occured, we log the error to the console at this time.

Post Request

A Post request is used mostly to send data to a server. To send post request, the axios.post() method is called. This method accepts an endpoint and information to be sent to the server.

Here is an simple example of how to make a post request with Axios.

axios.post('https://api.example.com/posts', {
  title: 'New Post',
  content: 'Lorem ipsum dolor sit amet.',

})
  .then(response => {
    console.log(response.data);      // The response body
  })
  .catch(error => {
    console.error(error);
  });

In this example, the second parameter is the body data to be sent to the server. This request tells the server that a new post will be created. If the server responds to this request without any problems, we print the response data to the console; otherwise, we print the error to the console.

Put Request

A Put request is used to replace or update the data with target source. This request is made with the help of axios.put() method. This method also accepts an endpoint URL and a javascript object holding data to replace.

Here is the example of how to send put request with axios.

axios.put('https://api.example.com/posts/1', {
  title: 'Updated Post',
  content: 'Lorem ipsum dolor sit amet.',

})
  .then(response => {
    console.log(response.data);  // The updated resource data
  })
  .catch(error => {
    console.error(error);
  });

This request tells to the server that the content of the post with the unique identifier 1 will be replaced by data we provide as a second parameter. If everything is ok, we print the respond data to the console, otherwise we log to the error to the console to learn what’s going on.

Delete Request

A delete request is used to remove a specific data in target source. This task is performed with axios.delete() method. Here is an example of how to make a delete request with Axios.

axios.delete('https://api.example.com/posts/1')
  .then(response => {
    console.log(response.status);    // The HTTP status code
  })
  .catch(error => {
    console.error(error);
  });

This request indicates that the post with the unique identifier 1 to be removed on the source. After the server perform the operation, it sends a respond and we print it to the console.

Response and Error Objects

As mentioned above, when we make an HTTP request, the server performs operations based on the request, and subsequently responds to it. Axios returns this response as a promise that is resolved with the response and error object. That’s why we used then and catch blocks.

These resolved objects not only contain data and error but also containt different properties as shown below.

axios.get('https://api.example.com/posts')
  .then(response => {
    console.log(response.data);      // The updated resource data
    console.log(response.status);    // The HTTP status code
    console.log(response.statusText);// The status message
    console.log(response.headers);   // The response headers
  })
  .catch(error => {
    console.error(error.message);          // The error message
    console.log(error.response.status);    // The HTTP status code
    console.log(error.response.data);      // The response body
    console.log(error.response.headers);   // The response headers
  });

Response Object

The response object contains various properties that provide information about the response to request sent.

  • data: This property contains the response body returned by the server. It could be an object, an array or any other data type depending on the server’s response.
  • status: This property represents the HTTP status code of the response. For example, 200 indicates a successful request, 404 indicates a resource not found and so on.
  • statusText: This property provides the corresponding status message associated with the status code. For a 200 status code, it will be “OK”.
  • headers: This property holds the response headers returned by the server. It is an object containing key-value pairs representing the header names and their respective values.
  • config: This property contains the request configuration used to make the request. It includes information such as the request URL, HTTP method, headers and other settings.

Error Object

When an error occurs during an Axios request, the error object provides useful information about the error. Here’re its properties

error.message: This property contains the error message associated with the error.

error.response: If the server responds with an error status code (4xx or 5xx), Axios includes the response property in the error object. This property contains information about the response, including the status code, response body and headers.

error.response.status: The HTTP status code of the response.

error.response.data: The response body returned by the server.

error.response.headers: The headers included in the response.

How To Send Form Data

If you have a form and you want to send that form data to a server, you can include the data provided by the form as part of a POST request.

In Below, we have a simple HTML form element including a submit button and two inputs for getting name and email information from user.

<form id="myForm">
  <input type="text" name="name" placeholder="Name">
  <input type="email" name="email" placeholder="Email">
  <button type="submit">Submit</button>
</form>

When the user press enter or click the submit button, the following code snippet will trigger. This script firstly capture the form data with the FormData object and send this data to the server over an endpoint.

document.getElementById('myForm').addEventListener('submit', function(event) {
  event.preventDefault(); // Prevent the default form submission
  const formData = new FormData(event.target); // Capture the form data
  axios.post('https://api.example.com/submit', formData)
    .then(response => {
      console.log(response.data);      // The response data
      // Reset the form after successful submission
      event.target.reset();
    })
    .catch(error => {
      console.error(error);
    });

});

Sending Headers with Axios

Headers are additional pieces of information sent along with a request or response. Headers provide metadata about the data being sent. To send headers with Axios, you can include them as an object in the request configuration.

const headers = {
  'Authorization': 'Bearer token',
  'Content-Type': 'application/json',
};
axios.get('https://api.example.com/posts', { headers })
  .then(response => {
    console.log(response.data);
  })
  .catch(error => {
    console.error(error);
  });

Tokens are essential parts of authentication systems and they are sent to server with almost every queries using the request header for checking some credentials in the server. Therefore, in this example, we’re including an authorization header with a bearer token and setting the content type to JSON so that server can check if the request is authorized.

Send Two Or Multiple Requests At Once

Sometimes, we need to send multiple requests to an API for fetching multiple source or submitting multiple information. At this point, we can send multiple requests to different endpoints at once. Here’s an example of how to use the axios.all method to perform this task

const request1 = axios.get('https://api.example.com/posts/1');
const request2 = axios.get('https://api.example.com/posts/2');
const request3 = axios.get('https://api.example.com/posts/3');

axios.all([request1, request2, request3])
  .then(responses => {
    const response1 = responses[0];
    const response2 = responses[1];
    const response3 = responses[2];

    console.log(response1.data);      // Data from the first request
    console.log(response2.data);      // Data from the second request
    console.log(response3.data);      // Data from the third request
  })
  .catch(error => {
    console.error(error);
  });

Request And Response Interceptors

Interceptors allow us to intercept and transform requests or responses globally or on a per-request basis. You can add interceptors to modify headers, transform data, handle errors or perform any custom logic. Here’s an example of adding a request interceptor to include an authorization token:

axios.interceptors.request.use(config => {
  config.headers.Authorization = `Bearer ${getToken()}`;
  return config;
});

Whenever a request is made using Axios, this interceptor will be triggered. This interceptor simply put the authorization token into the request header for sending the server.

Similarly, you can add a response interceptor to handle common error scenarios:

axios.interceptors.response.use(response => {
  return response;
}, error => {
  if (error.response.status === 401) {
    // Redirect to login page
  }
  return Promise.reject(error);
});

This code snippet enables us to handle globally unauthorized requests specified with the 401 status code by redirecting users to the login page of the application.

Axios Request Config

We have used some methods for sending request for each type of request, however, we can also create a config object and pass it to axios method for sending configured requests. Here is an example:

axios({
  method: 'get',
  url: 'https://api.example.com/posts',
  params: { limit: 10 },
  headers: { 'Authorization': 'Bearer token' },
  timeout: 5000,
  responseType: 'json'
})
  .then(response => {
    // Handle the response
  })
  .catch(error => {
    // Handle the error
  });

The snippet above can be used to send get request to the endpoint https://api.example.com/posts with an authorization header, params object and other configuration values. These object properties are only a few example you can find more properties here.

Axios Default Property

In Axios, you can set default values for the configuration of your requests using the defaults object. This allows define common settings that will be applied to all requests.

import axios from 'axios';

// Set default base URL
axios.defaults.baseURL = 'https://api.example.com';

// Set default headers
axios.defaults.headers.common['Authorization'] = 'Bearer token';

// Set default timeout
axios.defaults.timeout = 5000;

By setting these default values, you don’t need to specify them in each request. However, you can still override these configuration settings for individual requests

Axios Over Fetch

As you may know ,you can also send request with fetch api in browser environment. So you can wonder differences between them. Here is an outline for differences:

  • Axios has simpler API
  • Fetch API requires extra configuration
  • Axios works in browser and node environment but fetch works only in browsers
  • Axios allows us global configuration

Simply put, axios provides a simpler way to working with servers and APIs than fetch API.

Axios With Javascript Frameworks

Axios is widely used with various JavaScript frameworks and libraries such as react, vue and angular to make HTTP requests. Nothing changes, you can use axios as you use it with javascript or Nodejs. Here is an example of axios with react to give you an insight.

import React, { useEffect, useState } from 'react';
import axios from 'axios';

const MyComponent = () => {

  const [data, setData] = useState([]);
  useEffect(() => {

    // Function to fetch data
    const fetchData = async () => {
      try {
        const response = await axios.get('https://api.example.com/posts');
        setData(response.data);
      } catch (error) {
        console.error(error);
      }
    };
    
    fetchData();
  }, []);

  return (
    <div>
      <h1>My Component</h1>
      {data.map(item => (
        <p key={item.id}>{item.title}</p>
      ))}
    </div>

  );

};

export default MyComponent;

In this example, when component is rendered, axios send request to the specified URL and data variable is updated with data coming from server, enabling to update the page.

Conclusion

Axios is a powerful HTTP client API based on the XMLHttpRequest object in JavaScript. It provides useful methods for sending HTTP requests (GET, POST, PUT, DELETE) and easy handling of responses and errors. It allows us to configure our requests both on a locally and globally basis, which helps us to make requests with ease.

Thank you for reading.