Axios is a powerful and easy-to-use HTTP client for JavaScript, commonly used in frontend and backend applications for making HTTP requests. This cheat sheet covers the most commonly used features and best practices.
1. Installation
Install Axios using npm, yarn, or 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>
2. Making GET Requests
import axios from 'axios';
axios.get('https://jsonplaceholder.typicode.com/posts')
.then(response => console.log(response.data))
.catch(error => console.error(error));
3. Making POST Requests
axios.post('https://jsonplaceholder.typicode.com/posts', {
title: 'Axios Cheat Sheet',
body: 'This is a sample post request.',
userId: 1
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
4. PUT and PATCH Requests
- PUT replaces the entire resource:
axios.put('https://jsonplaceholder.typicode.com/posts/1', {
title: 'Updated Title',
body: 'Updated body text.',
userId: 1
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
- PATCH updates only specific fields:
axios.patch('https://jsonplaceholder.typicode.com/posts/1', {
title: 'Partially Updated Title'
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
5. DELETE Requests
axios.delete('https://jsonplaceholder.typicode.com/posts/1')
.then(response => console.log('Deleted successfully'))
.catch(error => console.error(error));
6. Setting Headers
axios.get('https://jsonplaceholder.typicode.com/posts', {
headers: {
'Authorization': 'Bearer YOUR_ACCESS_TOKEN',
'Content-Type': 'application/json'
}
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
7. Handling Query Parameters
axios.get('https://jsonplaceholder.typicode.com/posts', {
params: {
userId: 1
}
})
.then(response => console.log(response.data))
.catch(error => console.error(error));
8. Using Axios Instances
const apiClient = axios.create({
baseURL: 'https://jsonplaceholder.typicode.com',
timeout: 1000,
headers: { 'Authorization': 'Bearer YOUR_ACCESS_TOKEN' }
});
apiClient.get('/posts')
.then(response => console.log(response.data))
.catch(error => console.error(error));
9. Handling Errors Gracefully
axios.get('https://jsonplaceholder.typicode.com/posts/invalid')
.then(response => console.log(response.data))
.catch(error => {
if (error.response) {
console.error('Server responded with:', error.response.status);
} else if (error.request) {
console.error('No response received:', error.request);
} else {
console.error('Error setting up request:', error.message);
}
});
10. Interceptors for Request and Response
axios.interceptors.request.use(config => {
console.log('Request sent at:', new Date().toISOString());
return config;
}, error => Promise.reject(error));
axios.interceptors.response.use(response => {
console.log('Response received:', response);
return response;
}, error => Promise.reject(error));
11. Cancelling Requests
const controller = new AbortController();
axios.get('https://jsonplaceholder.typicode.com/posts', { signal: controller.signal })
.then(response => console.log(response.data))
.catch(error => console.error(error));
// Cancel the request
controller.abort();
12. Concurrent Requests
axios.all([
axios.get('https://jsonplaceholder.typicode.com/posts/1'),
axios.get('https://jsonplaceholder.typicode.com/posts/2')
])
.then(axios.spread((post1, post2) => {
console.log('Post 1:', post1.data);
console.log('Post 2:', post2.data);
}))
.catch(error => console.error(error));
Conclusion
Axios isn't just another HTTP client—it's your digital henchman, fetching data, sending payloads, and handling errors like a seasoned assassin. Whether you're on the frontend or backend battlefield, this cheat sheet arms you with the firepower to dominate API interactions. Keep it close, or risk drowning in a sea of failed requests and endless debugging nightmares.
Top comments (0)