Axios is a popular JavaScript library used for making HTTP requests. It provides a clean, promise-based API to interact with RESTful endpoints and other data sources. Whether you’re working with Node.js or in the browser, Axios simplifies data fetching, sending requests, and error handling.
Table of Contents
Section | Topic |
---|---|
1 | Introduction to Axios |
2 | Installation |
3 | Features of Axios |
4 | Making HTTP Requests |
4.1 | GET Requests |
4.2 | POST Requests |
4.3 | PUT Requests |
4.4 | DELETE Requests |
5 | Axios Configuration |
5.1 | Global Configuration |
5.2 | Instance Configuration |
6 | Handling Responses |
6.1 | Response Data |
6.2 | Response Headers |
7 | Error Handling |
8 | Axios Interceptors |
9 | Working with Headers |
10 | Canceling Requests |
11 | Using Axios with Async/Await |
12 | Handling Timeouts |
13 | Uploading and Downloading Files |
14 | Axios and Authentication |
14.1 | Token-Based Authentication |
14.2 | Cookies and Session Management |
15 | Advanced Axios Use Cases |
15.1 | Retry Requests |
15.2 | Request Queues |
16 | Comparing Axios to Fetch API |
17 | Conclusion |
1. Introduction to Axios
Axios is a promise-based HTTP client for JavaScript. It is designed to work both in the browser and in Node.js, making it highly versatile for web and backend development. Axios helps developers handle asynchronous data fetching and provides utility features to simplify the process of working with APIs.
Key Features
- Promise-based API: Leverages modern JavaScript promises for easier asynchronous handling.
- Built-in JSON transformation: Automatically converts request and response data to JSON.
- Interceptors: Middleware-like functionality for transforming requests and responses.
- Global configuration: Easily set default headers, base URLs, and other settings.
- Browser support: Handles cross-browser issues seamlessly.
2. Installation
Axios can be installed via npm, yarn, or directly included via a CDN.
Using npm
npm install axios
Using yarn
yarn add axios
Using a CDN
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
After installation, you can import Axios in your JavaScript files:
const axios = require('axios'); // CommonJS
import axios from 'axios'; // ES6 Modules
3. Features of Axios
3.1 Request Methods
Axios supports all standard HTTP methods: GET, POST, PUT, DELETE, PATCH, and OPTIONS.
3.2 Default Configuration
Set default headers, base URLs, and timeout settings for all requests.
3.3 Request and Response Interceptors
Intercept and transform requests or responses before they are sent or processed.
3.4 Error Handling
Provides detailed error objects with status codes, headers, and request data.
3.5 Supports Promises and Async/Await
Simplifies asynchronous operations with modern JavaScript syntax.
4. Making HTTP Requests
4.1 GET Requests
GET requests retrieve data from a server.
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
GET with Query Parameters
axios.get('https://jsonplaceholder.typicode.com/posts', {
params: {
userId: 1
}
})
.then(response => {
console.log(response.data);
});
4.2 POST Requests
POST requests send data to a server.
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'foo',
body: 'bar',
userId: 1
})
.then(response => {
console.log(response.data);
});
4.3 PUT Requests
PUT requests update existing resources.
axios.put('https://jsonplaceholder.typicode.com/posts/1', {
title: 'updated title',
body: 'updated body',
})
.then(response => {
console.log(response.data);
});
4.4 DELETE Requests
DELETE requests remove resources.
axios.delete('https://jsonplaceholder.typicode.com/posts/1')
.then(response => {
console.log('Resource deleted');
});
5. Axios Configuration
5.1 Global Configuration
axios.defaults.baseURL = 'https://api.example.com';
axios.defaults.headers.common['Authorization'] = 'Bearer token';
axios.defaults.timeout = 10000; // 10 seconds
5.2 Instance Configuration
const instance = axios.create({
baseURL: 'https://api.another.com',
timeout: 5000,
headers: {'X-Custom-Header': 'foobar'}
});
instance.get('/data')
.then(response => {
console.log(response.data);
});
6. Handling Responses
6.1 Response Data
Axios wraps server responses in an object containing the data
, status
, statusText
, headers
, and config
.
axios.get('/endpoint')
.then(response => {
console.log(response.data); // Actual data
console.log(response.status); // HTTP status code
});
6.2 Response Headers
axios.get('/endpoint')
.then(response => {
console.log(response.headers);
});
7. Error Handling
Axios provides a detailed error object for failed requests.
axios.get('/nonexistent')
.catch(error => {
if (error.response) {
console.error('Response error:', error.response.data);
} else if (error.request) {
console.error('Request error:', error.request);
} else {
console.error('Error', error.message);
}
});
8. Axios Interceptors
Axios interceptors are a powerful feature that allows you to modify requests and responses globally before they are sent to the server or received by the application. Interceptors act as middleware, providing a centralized way to handle common tasks like authentication, logging, or transforming data.
Why Use Axios Interceptors?
Interceptors streamline repetitive tasks in API interactions, offering benefits such as:
- Centralized Logic: Avoid duplicating logic across multiple requests or responses.
- Preprocessing Requests: Modify or enrich request data before it reaches the server.
- Postprocessing Responses: Transform or validate response data before using it.
- Error Handling: Manage API errors in a standardized way.
Request Interceptor
axios.interceptors.request.use(config => {
config.headers['Authorization'] = 'Bearer token';
return config;
});
Response Interceptor
axios.interceptors.response.use(response => {
return response;
}, error => {
return Promise.reject(error);
});
Example:
axios.interceptors.request.use((config) => {
const token = localStorage.getItem('authToken');
if (token) {
config.headers['Authorization'] = `Bearer ${token}`;
}
return config;
}, (error) => {
return Promise.reject(error);
});
axios.interceptors.response.use((response) => {
return response;
}, (error) => {
if (error.response) {
switch (error.response.status) {
case 401:
console.error('Unauthorized! Redirecting to login.');
window.location.href = '/login';
break;
case 500:
console.error('Server error! Try again later.');
break;
default:
console.error('Unexpected error:', error.response.data);
}
}
return Promise.reject(error);
});
Managing Multiple Interceptors
Sometimes, you may need to add multiple interceptors for different purposes. Axios provides a use
method to register them sequentially. Interceptors execute in the order they are added for requests and in reverse order for responses.
axios.interceptors.request.use((config) => {
console.log('First request interceptor');
return config;
});
axios.interceptors.request.use((config) => {
console.log('Second request interceptor');
return config;
});
axios.interceptors.response.use((response) => {
console.log('First response interceptor');
return response;
});
axios.interceptors.response.use((response) => {
console.log('Second response interceptor');
return response;
});
Removing Axios Interceptors
You can remove interceptors using the eject
method, which takes the interceptor’s ID as an argument. The use
method returns this ID when registering the interceptor.
const requestInterceptor = axios.interceptors.request.use((config) => {
console.log('Request intercepted');
return config;
});
// Remove the interceptor later
axios.interceptors.request.eject(requestInterceptor);
9. Working with Headers
Custom headers can be set at the request or global level.
axios.get('/endpoint', {
headers: {
'X-Requested-With': 'XMLHttpRequest'
}
});
10. Canceling Requests
const controller = new AbortController();
axios.get('/endpoint', {
signal: controller.signal
})
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request canceled');
}
});
controller.abort();
11. Using Axios with Async/Await
When working with Axios, the combination of async/await
syntax can make asynchronous operations more intuitive and readable compared to chaining .then()
and .catch()
. This modern JavaScript feature simplifies handling promises, providing cleaner and more maintainable code, especially for complex API workflows.
Why Use Async/Await with Axios?
- Improved Readability: Code written with
async/await
is more sequential and resembles synchronous logic, making it easier to understand. - Error Handling: Simplifies try-catch blocks for handling errors compared to
.catch()
in promise chains. - Chaining Multiple Requests: Makes it easier to handle multiple dependent API calls sequentially or concurrently.
- Cleaner Code: Reduces nested code, which improves readability and maintainability.
(async () => {
try {
const response = await axios.get('/endpoint');
console.log(response.data);
} catch (error) {
console.error(error);
}
})();
Handling Multiple Requests with Async/Await
1. Sequential Requests
You can make multiple API calls sequentially using await
.
const fetchSequentialData = async () => {
try {
const users = await axios.get('url');
console.log('Users:', users.data);
const posts = await axios.get('url');
console.log('Posts:', posts.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchSequentialData();
2. Concurrent Requests
To make multiple requests concurrently, use Promise.all
with await
.
const fetchConcurrentData = async () => {
try {
const [users, posts] = await Promise.all([
axios.get('url'),
axios.get('url'),
]);
console.log('Users:', users.data);
console.log('Posts:', posts.data);
} catch (error) {
console.error('Error fetching data:', error);
}
};
fetchConcurrentData();
Best Practices for Using Async/Await with Axios
- Always Use Try-Catch: Prevent unhandled promise rejections by wrapping
await
calls in atry-catch
block. - Centralize Axios Configuration: Use a custom Axios instance with predefined settings to avoid redundant configurations.
- Leverage Async/Await for Clarity: Prefer
async/await
for complex workflows to make code more readable and maintainable. - Handle Errors Gracefully: Implement detailed error-handling strategies based on HTTP status codes or other response attributes.
- Avoid Blocking Code: Use concurrent requests with
Promise.all
to improve performance when fetching independent data.
12. Handling Timeouts
axios.get('/endpoint', {
timeout: 5000 // 5 seconds
})
.catch(error => {
if (error.code === 'ECONNABORTED') {
console.log('Request timeout');
}
});
13. Uploading and Downloading Files
Uploading Files
const formData = new FormData();
formData.append('file', file);
axios.post('/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
});
Downloading Files
axios.get('/file', {
responseType: 'blob'
})
.then(response => {
const url = URL.createObjectURL(response.data);
const link = document.createElement('a');
link.href = url;
link.download = 'filename';
link.click();
});
14. Axios and Authentication
Token-Based Authentication
Bearer tokens are widely used in APIs for token-based authentication. You include the token in the Authorization
header of your requests.
const axiosInstance = axios.create({
baseURL: 'URL',
headers: {
'Authorization': 'Bearer your-token-here',
},
});
axiosInstance.get('/protected-resource')
.then(response => {
console.log('Data:', response.data);
})
.catch(error => {
console.error('Error:', error);
});
Cookies and Session Management
Some APIs use cookies to manage user sessions. Axios supports cookies by setting the withCredentials
option to true
.
axios.defaults.withCredentials = true;
axios.get('URL')
.then(response => {
console.log('Data:', response.data);
})
.catch(error => {
console.error('Error:', error);
});
// Example - Login with cookies
const login = async () => {
try {
const response = await axios.post('https://api.example.com/login', {
username: 'your-username',
password: 'your-password',
}, {
withCredentials: true, // Ensures cookies are sent with requests
});
console.log('Login successful:', response.data);
} catch (error) {
console.error('Login failed:', error);
}
};
login();
15. Advanced Axios Use Cases
Retry Requests
const axiosRetry = require('axios-retry');
axiosRetry(axios, { retries: 3 });
Request Queues
const queue = [];
function processQueue() {
while (queue.length) {
const req = queue.shift();
req();
}
}
queue.push(() => axios.get('/data'));
processQueue();
16. Comparing Axios to Fetch API
Feature | Axios | Fetch |
---|---|---|
Promise-based | Yes | Yes |
Interceptors | Yes | No |
JSON Handling | Automatic | Manual |
Node.js Support | Yes | No |
Error Handling | Built-in | Limited |
17. Conclusion
Axios is a powerful library that simplifies HTTP requests and error handling in JavaScript applications. Its rich feature set and ease of use make it a great choice for developers building web or Node.js applications.
Check our more blogs
Top Contents
1. NextJs – Server-Side Rendering
4. React Hooks
Latest Post
Email Template Design for Discount Summary
Enjoy 25% off from all purchases discount Exclusive Discounts Just For You! Lorem ipsum dolor…
Email Template For Travel Agency
Book Your Trip Lorem ipsum dolor sit amet, con sectetur adip iscing elit sed do…
Event Email Template Design
14/01/2025 Join us to watch WTF Episode 11 REGISTER NOW     Why should you…
kite festival email template
Kite Festival Email template: Email templates used for communication across personal, professional, and marketing domains.…
React context API
Introduction to React Context API The React Context API is a powerful feature introduced in…
Password Generator
A password generator is a tool designed to create strong, unique passwords for securing online…
Axios
Axios is a popular JavaScript library used for making HTTP requests. It provides a clean,…
How to make a chrome extension?
Google Chrome extensions are small programs that enhance browser functionality, making tasks more efficient and…
Git cherry pick
git cherry pick is a powerful command in Git that allows you to apply changes…
Delete branch in GitHub
What is a GitHub Branch? A branch in GitHub represents an independent line of development…