Open In App

What Is Axios?

Last Updated : 30 Aug, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Axios is a popular open-source JavaScript library used to make HTTP requests from web browsers or Node.js environments. It simplifies the process of sending asynchronous HTTP requests to REST endpoints, handling responses, and performing various network-related tasks.

Built on top of JavaScript’s native XMLHttpRequest and the fetch API, Axios offers a more user-friendly API with features like interceptors, automatic JSON data transformation, error handling, and support for older browsers.

Key Features of Axios

  • Promise-Based: Axios uses Promises, making it easier to handle asynchronous requests with modern JavaScript features like async/await.
  • Interceptors: Allows you to intercept and modify requests or responses before they are handled by .then() or .catch().
  • Automatic JSON Data Transformation: Automatically transforms JSON data to JavaScript objects, making data manipulation simpler.
  • Request and Response Timeout: Enables setting timeouts to avoid hanging requests.
  • Cancel Requests: Allows cancellation of requests to manage resources effectively.
  • Error Handling: Provides a structured way to handle HTTP errors using the catch() method.
  • Supports All HTTP Methods: Including GET, POST, PUT, DELETE, PATCH, and more.
  • Cross-Site Request Forgery (CSRF) Protection: Easily supports security features like CSRF by managing tokens.

Installation and Setup

You can install Axios using npm (Node Package Manager) or directly include it in your HTML file.

Step 1: Installing via npm

To install Axios in a Node.js project, run:

npm install axios

Step 2: Including in HTML

For use in a browser environment, include Axios via a CDN link in your HTML file:

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

Basic Usage of Axios

Using Axios is straightforward and intuitive. Here is a basic example of making a GET request to fetch data from an API.

1. Making a GET Request

const axios = require('axios'); 

// Making a GET request
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error fetching data:', error);
});

2. Making a POST Request

// Making a POST request
axios.post('https://api.example.com/data', {
name: 'John Doe',
age: 30
})
.then(response => {
console.log('Data posted successfully:', response.data);
})
.catch(error => {
console.error('Error posting data:', error);
});

Advanced Features of Axios

1. Configuring Global Defaults

You can set default configuration options for Axios requests. For example:

axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';
axios.defaults.timeout = 5000; // Set a timeout for requests

2. Using Interceptors

Interceptors allow you to perform actions or modifications before a request is sent or after a response is received:

// Add a request interceptor
axios.interceptors.request.use(
function (config) {
console.log('Request sent at:', new Date());
return config;
},
function (error) {
return Promise.reject(error);
}
);

// Add a response interceptor
axios.interceptors.response.use(
function (response) {
return response;
},
function (error) {
return Promise.reject(error);
}
);

3. Cancelling Requests

If you need to cancel an ongoing request, you can use the CancelToken feature:

const CancelToken = axios.CancelToken;
const source = CancelToken.source();

axios.get('https://api.example.com/data', { cancelToken: source.token })
.then(response => {
console.log(response.data);
})
.catch(thrown => {
if (axios.isCancel(thrown)) {
console.log('Request canceled', thrown.message);
} else {
console.error('Error:', thrown);
}
});

// Cancel the request
source.cancel('Request canceled by the user.');

4. Handling Errors

Axios provides an easy way to handle errors with the catch block:

axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
if (error.response) {
console.error('Error data:', error.response.data);
console.error('Error status:', error.response.status);
console.error('Error headers:', error.response.headers);
} else if (error.request) {
console.error('Request error:', error.request);
} else {
console.error('Error message:', error.message);
}
});

Step-by-Step Implementation

Step 1: Setup the Project

Create a simple HTML file and a JavaScript file.

index.html: The HTML file will include a basic structure with a button to fetch users, a list to display the data, and a form to add a new user.

app.js: The JavaScript file will handle the logic for making HTTP requests using Axios.

Step 2: Create the HTML Structure

Create an index.html file with the following content:

HTML
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Axios Example</title>
    <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
</head>

<body>
    <h1>Axios Demo: Fetch and Add Users</h1>

    <button id="fetch-users">Fetch Users</button>

    <ul id="user-list"></ul>

    <h2>Add New User</h2>
    <form id="user-form">
        <input type="text" id="name" placeholder="Name" required>
        <input type="email" id="email" placeholder="Email" required>
        <button type="submit">Add User</button>
    </form>

    <script src="app.js"></script>
</body>

</html>

3. Create the JavaScript File

Create an app.js file with the following content:

JavaScript
document.addEventListener('DOMContentLoaded', function () {
    // Base URL for JSONPlaceholder API (a free public API)
    const apiUrl = 'https://jsonplaceholder.typicode.com/users';

    // Fetch and display users
    document.getElementById('fetch-users').addEventListener('click', function () {
        axios.get(apiUrl)
            .then(response => {
                const users = response.data;
                const userList = document.getElementById('user-list');
                userList.innerHTML = ''; 

                // Display each user
                users.forEach(user => {
                    const listItem = document.createElement('li');
                    listItem.textContent = `${user.name} - ${user.email}`;
                    userList.appendChild(listItem);
                });
            })
            .catch(error => {
                console.error('Error fetching users:', error);
            });
    });

    // Add a new user
    document.getElementById('user-form').addEventListener('submit', function (e) {
        e.preventDefault(); 

        const name = document.getElementById('name').value;
        const email = document.getElementById('email').value;

        axios.post(apiUrl, { name, email })
            .then(response => {
                console.log('User added successfully:', response.data);
                alert('User added successfully!');
            })
            .catch(error => {
                console.error('Error adding user:', error);
            });
    });
});

Explanation of the Code

  • Fetching Users with Axios (GET Request)
    • The axios.get(apiUrl) call retrieves data from the API endpoint.
    • On success (.then()), it processes the response data and updates the DOM by appending each user to a list.
    • On error (.catch()), it logs the error to the console.
  • Adding a New User with Axios (POST Request)
    • The form submission is intercepted using e.preventDefault() to prevent the default page reload.
    • axios.post(apiUrl, { name, email }) sends a POST request to the API to add a new user.
    • If successful, it displays a success message; otherwise, it logs the error.

Testing the Application

  • Open the index.html file in your web browser.
  • Click the Fetch Users button to load and display user data.
  • Fill in the form to add a new user and click Add User.

Output:

Benefits of Using Axios

  • Simplified Syntax: Axios provides a cleaner and simpler syntax compared to the native fetch API.
  • Consistent Data Handling: Automatically transforms JSON data to JavaScript objects.
  • Cross-Browser Compatibility: Works with older browsers that do not support the native fetch API.
  • Enhanced Security: Supports CSRF protection and other security features.
  • Versatile and Powerful: Suitable for both client-side and server-side environments, making it a versatile tool for developers.

Next Article

Similar Reads

three90RightbarBannerImg