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
What Is Axios?
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 na
5 min read
Axios in React Native
Axios is a widely used HTTP client for making REST API calls. You can use this in React Native to get data from any REST API. Axios in React NativeAxios in React Native is used to send the HTTP requests from the mobile devices to the server to send and receive data using the api endpoints. Syntax://
4 min read
What is Kaggle?
Kaggle is a powerful online platform where the data science and machine learning community comes together. Launched in 2010, Kaggle provides a place in which data scientists, analysts, and machine learning enthusiasts can work on real-world problems, share knowledge, and participate in competitions.
8 min read
What is MongoDB Atlas?
MongoDB Atlas is a fully-managed cloud database service provided by MongoDB, designed to simplify database management for developers. With MongoDB Atlas, we can automate complex database tasks like scaling, backups, and security while focusing on building modern applications. It supports deployment
7 min read
What is Express Connect ?
Express Connect is a middleware for the Express.js web application framework for Node.js that allows you to easily connect to external APIs and other web applications. It provides a simple interface for making HTTP requests and can be used to retrieve data from APIs, post data to web applications, a
8 min read
ReactJS CORS Options
In ReactJS, Cross-Origin Resource Sharing or CORS requests refers to the method that allows you to make requests to the server deployed at a different domain. As a reference, if the frontend and backend are at two different domains, we need CORS there. Handling Cross-Origin Resource Sharing (CORS) i
3 min read
Axios in React: A Guide for Beginners
React is one of the most popular JavaScript libraries for building user interfaces, and it works seamlessly with various data-fetching tools. Among these tools, Axios stands out as one of the easiest and most efficient libraries for making HTTP requests in React. In this article, weâll explore how t
6 min read
Node.js Basics
NodeJS is a powerful and efficient open-source runtime environment built on Chrome's V8 JavaScript engine. It allows developers to run JavaScript on the server side, which helps in the creation of scalable and high-performance web applications. In this article, we will discuss the NodeJs Basics and
7 min read
What Is Edge AI? Benefits and Use Cases
Edge AI is the integration of artificial intelligence (AI) with edge computing, enabling data processing and decision-making to happen on devices close to the source of data rather than relying on centralized cloud servers. This paradigm shift allows AI-powered devices to function efficiently in rea
6 min read
Weather Application using ReactJS
In this article, we will develop an Interactive Weather Application using ReactJS Framework. The developed application will provide real-time weather information to the user for the city they have searched. If the user searches, for the wrong city, an Error message is also displayed to the user, sta
5 min read