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.
Similar Reads
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Spring Boot Tutorial
Spring Boot is a Java framework that makes it easier to create and run Java applications. It simplifies the configuration and setup process, allowing developers to focus more on writing code for their applications. This Spring Boot Tutorial is a comprehensive guide that covers both basic and advance
10 min read
Class Diagram | Unified Modeling Language (UML)
A UML class diagram is a visual tool that represents the structure of a system by showing its classes, attributes, methods, and the relationships between them. It helps everyone involved in a projectâlike developers and designersâunderstand how the system is organized and how its components interact
12 min read
HTML Tutorial
HTML stands for HyperText Markup Language. It is the standard language used to create and structure content on the web. It tells the web browser how to display text, links, images, and other forms of multimedia on a webpage. HTML sets up the basic structure of a website, and then CSS and JavaScript
11 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Backpropagation in Neural Network
Back Propagation is also known as "Backward Propagation of Errors" is a method used to train neural network . Its goal is to reduce the difference between the modelâs predicted output and the actual output by adjusting the weights and biases in the network.It works iteratively to adjust weights and
9 min read
Polymorphism in Java
Polymorphism in Java is one of the core concepts in object-oriented programming (OOP) that allows objects to behave differently based on their specific class type. The word polymorphism means having many forms, and it comes from the Greek words poly (many) and morph (forms), this means one entity ca
7 min read
3-Phase Inverter
An inverter is a fundamental electrical device designed primarily for the conversion of direct current into alternating current . This versatile device , also known as a variable frequency drive , plays a vital role in a wide range of applications , including variable frequency drives and high power
13 min read
What is Vacuum Circuit Breaker?
A vacuum circuit breaker is a type of breaker that utilizes a vacuum as the medium to extinguish electrical arcs. Within this circuit breaker, there is a vacuum interrupter that houses the stationary and mobile contacts in a permanently sealed enclosure. When the contacts are separated in a high vac
13 min read
AVL Tree Data Structure
An AVL tree defined as a self-balancing Binary Search Tree (BST) where the difference between heights of left and right subtrees for any node cannot be more than one. The absolute difference between the heights of the left subtree and the right subtree for any node is known as the balance factor of
4 min read