Here’s a basic cheat sheet for Axios, a popular JavaScript library for making HTTP requests:
Installing Axios
You can install Axios using npm or yarn:
# Using npm
npm install axios
# Using yarn
yarn add axios
Importing Axios
Import Axios into your JavaScript/TypeScript file:
// CommonJS
const axios = require('axios');
// ES6+ (using import)
import axios from 'axios';
Making GET Requests
Making a simple GET request:
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
Handling Query Parameters
Adding query parameters to a GET request:
axios.get('https://api.example.com/data', {
params: {
param1: 'value1',
param2: 'value2',
},
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
Making POST Requests
Making a simple POST request:
axios.post('https://api.example.com/data', {
key1: 'value1',
key2: 'value2',
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
Handling Headers
Setting custom headers:
axios.get('https://api.example.com/data', {
headers: {
'Content-Type': 'application/json',
'Authorization': 'Bearer YourAccessToken',
},
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
Handling Response Interceptors
Applying interceptors to handle responses globally:
axios.interceptors.response.use(
response => response,
error => {
console.error(error);
return Promise.reject(error);
}
);
Handling Request Timeouts
Setting a timeout for a request:
axios.get('https://api.example.com/data', {
timeout: 5000, // 5 seconds
})
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error(error);
});
Handling Concurrent Requests
Making multiple requests concurrently:
const request1 = axios.get('https://api.example.com/data1');
const request2 = axios.get('https://api.example.com/data2');
axios.all([request1, request2])
.then(axios.spread((response1, response2) => {
console.log(response1.data, response2.data);
}))
.catch(error => {
console.error(error);
});
Handling Cancelation
Canceling a request using CancelToken
:
const source = axios.CancelToken.source();
axios.get('https://api.example.com/data', {
cancelToken: source.token,
})
.then(response => {
console.log(response.data);
})
.catch(error => {
if (axios.isCancel(error)) {
console.log('Request canceled', error.message);
} else {
console.error(error);
}
});
// To cancel the request
source.cancel('Request canceled by the user.');
This cheat sheet covers functionalities of Axios. Refer to the official Axios documentation for more advanced features and details.