Onjsdev Logo
Axios Tutorial for Beginners
14 Jul 20257 min read
HTTPJavaScriptNodejsReactjsAxios vs FetchAxios InstanceFetch API

Axios Tutorial for Beginners


Making HTTP requests is a fundametal requirement for almost every website. While there are various ways to make HTTP requests, with the nearly 107k stars on GitHub and 71 million weekly downloads on NPM, Axios is the most popular library that offers powerful features for this purpose.

In this article, we will explore how to install Axios, and various techniques for making HTTP requests with it.

What is Axios?

Axios is a promise-based HTTP client that provides easy-to-use set of methods for making HTTP requests to backend services over the HTTP/HTTPS protocol.

Under the hood, Axios uses the XMLHttpRequest object in browsers and the http module in Node.js. This makes it suitable for both server-side applications (like those built with Node.js) and client-side frameworks such as React, Vue, and Angular.

How To Install Axios?

You can add Axios to your project using different methods:

Using npm or yarn

You can use a package manager like npm or yarn to install it. Run the one of the following commands in your project directory.

npm install axios
yarn add axios

Using CDNs

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

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 the following script tag in your head tags.

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

How To Make HTTP Requests with Axios?

Once you have installed Axios, import it into your project.

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

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

Axios supports all major HTTP methods like GET, POST, PUT, DELETE and comes with built-in shorthand methods. Some of the most commonly used are:

Get Request

A GET request is used to retrieve data from a existing source. To send a GET request with Axios, you can use the axios.get() method. This method accepts an endpoint as its first 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 simply log the error to the console.

Post Request

A Post request is used to send data to a server. To send a post request with Axios, you can use the axios.post() method. This method accepts an endpoint and a javascript object holding data to be sent to the server.

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);
  });

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. You can use the axios.put() method to send a put request. This method also accepts an endpoint URL and a javascript object holding data to replace.

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. You can use the axios.delete() method to send a delete request.

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.

How To Handle Responses and Errors

As mentioned above, when you 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.

Here're its properties:

Error Object

On the other hand, if an error occurs during an Axios request, the error object provides useful information about the error.

Here're its properties:

How To Send Form Data

Not only you can send JSON data to a server with Axios, but you can also send form data.Simply include the data provided by the form as part of a POST request.

In the example 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);
    });
});

How To Send 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);
  });

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.

How To Send Two Or Multiple Requests At Once

Sometimes, you need to send multiple requests to an API for fetching multiple source or submitting multiple information. At this point, you 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 you 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 to the request header:

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

Whenever a request is made, 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. For example, you can handle common error scenarios like unauthorized requests:

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 you to handle globally unauthorized requests specified with the 401 status code by redirecting users to the login page of the application.

Axios Request Config

Axios offers different ways to send requests. Although it is not preferred in most applications, you can use the axios() method to send a request with a config object.

Here is an example:

axios({
  method: "get",
  url: "https://api.example.com/posts",
  headers: { Authorization: "Bearer token" },
})
  .then((response) => {
    // Handle the response
  })
  .catch((error) => {
    // Handle the error
  });

Axios Default Property

In Axios, you can set default values for the configuration of your requests using the defaults object. This allows you to 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 Instance

In addition to the global configuration, you can also create instances of Axios. This allows you to set pre-defined configurations for your requests.

const api = axios.create({
  baseURL: "https://api.example.com",
  headers: {
    "Content-Type": "application/json",
  },
});

api.get("/posts").then((response) => {
  console.log(response.data);
});

api.post("/posts", {
  title: "New Post",
  content: "Lorem ipsum dolor sit amet.",
});

You may find similar Axios instances and Axios defaults. However, they serve slightly different purposes. The axios.defaults object is used to set default configurations for all Axios requests globally. While requests made with axios instance are only applied to the request made with that instance.

That is, Axios instances allow you to encapsulate default configurations for a specific part of your application, meaning you can create various instances with different configurations for different purposes.

For more information, you can check Axios Instance article.

Axios vs Fetch

If you are a exact beginner, you may think that what's the difference between Axios and Fetch API.

Fetch API is a built-in tool in browsers to make HTTP requests. Unlike Axios, it requires extra configuration to work. Here is an example of how to use Fetch API to make a GET request:

fetch("https://api.example.com/posts")
  .then((response) => response.json())
  .then((data) => console.log(data))
  .catch((error) => console.error(error));

As you may notice, you need to manually parse the response data to JSON format. Axios does this automatically for you. This is a simple example, showing the requirement of extra configuration for 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 Browser 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 Browser and request module in Nodejs. It makes it easier to send HTTP requests and handle responses and errors. If you do not want to make extra configuration for Fetch API, you can give a try to Axios.

Thank you for reading.