Axios Cheatsheet
A User-friendly guide to making HTTP requests with Axios. Learn how to perform API calls, handle responses, and implement advanced features in your JavaScript applications.
Basic Setup
Installation & Import
Install Axios and import it into your project. You can use npm/yarn for installation or include it via CDN.
// Using npm
npm install axios
// Using yarn
yarn add axios
// Import in your file
import axios from 'axios';
// Or using CDN
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Create Instance
Create a custom Axios instance with default configurations for your API calls.
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000,
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer your-token-here'
}
});
Making Requests
Basic Requests
Different ways to make HTTP requests using Axios. These are the most common methods you'll use.
// GET request
axios.get('/users')
.then(response => console.log(response.data))
.catch(error => console.error(error));
// POST request
axios.post('/users', {
name: 'Mason',
email: 'mason@example.com'
});
// PUT request
axios.put('/users/1', {
name: 'Ethan'
});
// DELETE request
axios.delete('/users/1');
// Using async/await
async function getUser() {
try {
const response = await axios.get('/users/1');
return response.data;
} catch (error) {
console.error(error);
}
}
Request Configuration
Configure your requests with various options like parameters, headers, and timeout.
// URL Parameters
axios.get('/users', {
params: {
page: 1,
limit: 10,
sort: 'desc'
}
});
// Custom Headers
axios.post('/api/data', data, {
headers: {
'Authorization': 'Bearer token',
'Custom-Header': 'value'
},
timeout: 3000,
responseType: 'json'
});
Response Handling
Response Structure
Understanding the Axios response object and how to handle different types of responses.
axios.get('/api/data')
.then(response => {
// Response data
console.log(response.data);
// Status code
console.log(response.status);
// Status text
console.log(response.statusText);
// Response headers
console.log(response.headers);
// Request config
console.log(response.config);
});
// Error handling
axios.get('/api/data')
.catch(error => {
if (error.response) {
// Server responded with error
console.log(error.response.data);
console.log(error.response.status);
} else if (error.request) {
// Request made but no response
console.log(error.request);
} else {
// Error setting up request
console.log(error.message);
}
});
Global Response Handling
Set up interceptors to handle responses and errors globally across your application.
// Response interceptor
axios.interceptors.response.use(
response => {
// Modify response data
return response;
},
error => {
if (error.response.status === 401) {
// Handle unauthorized error
logout();
}
return Promise.reject(error);
}
);
// Request interceptor
axios.interceptors.request.use(
config => {
// Add token to headers
config.headers.Authorization = getToken();
return config;
},
error => {
return Promise.reject(error);
}
);
Advanced Features
Concurrent Requests
Make multiple requests simultaneously using axios.all() and axios.spread().
// Multiple concurrent requests
const getUser = () => axios.get('/user');
const getPosts = () => axios.get('/posts');
axios.all([getUser(), getPosts()])
.then(axios.spread((user, posts) => {
console.log('User', user.data);
console.log('Posts', posts.data);
}));
// Using async/await
async function getData() {
try {
const [user, posts] = await Promise.all([
axios.get('/user'),
axios.get('/posts')
]);
return { user: user.data, posts: posts.data };
} catch (error) {
console.error(error);
}
}
Request Cancellation
Cancel requests using cancel tokens, useful for preventing race conditions or stopping unnecessary requests.
// Create cancel token
const CancelToken = axios.CancelToken;
const source = CancelToken.source();
// Make cancellable request
axios.get('/api/data', {
cancelToken: source.token
}).catch(error => {
if (axios.isCancel(error)) {
console.log('Request cancelled:', error.message);
}
});
// Cancel the request
source.cancel('Operation cancelled by user');
// Using AbortController (modern browsers)
const controller = new AbortController();
axios.get('/api/data', {
signal: controller.signal
});
// Cancel request
controller.abort();
Error Handling & Retries
Try-Catch Pattern
Handle errors using try-catch blocks with async/await.
async function fetchUserData() {
try {
const response = await axios.get('/api/users/1');
return response.data;
} catch (error) {
if (error.response) {
// Handle specific HTTP errors
switch (error.response.status) {
case 404: throw new Error('User not found');
case 401: throw new Error('Please login again');
default: throw new Error('An error occurred');
}
}
throw error;
}
}
Retry Logic
Implement retry logic for failed requests.
async function fetchWithRetry(url, maxRetries = 3) {
for (let i = 0; i < maxRetries; i++) {
try {
return await axios.get(url);
} catch (error) {
if (i === maxRetries - 1) throw error;
// Wait before retrying (exponential backoff)
await new Promise(resolve =>
setTimeout(resolve, Math.pow(2, i) * 1000)
);
}
}
}