Axios
Detailed guide to using Axios for making HTTP requests in JavaScript with advanced configurations, error handling, and interceptors.
Axios
Axios is a popular, promise-based HTTP client for both browser and Node.js environments. It provides a clean and powerful API to make HTTP requests, handle responses, and manage errors, with more features and flexibility than the native Fetch API.
Why Axios?
Axios simplifies HTTP requests compared to fetch() by:
- Automatically transforming JSON data.
- Providing timeout support.
- Supporting request and response interceptors.
- Handling HTTP errors more intuitively.
- Simplifying cancellation of requests.
Installing Axios
Use npm or yarn to install Axios.
npm install axios
# or
yarn add axiosThen import it:
import axios from 'axios';Making a Basic GET Request
axios.get('https://api.example.com/data')
.then(response => {
console.log(response.data);
})
.catch(error => {
console.error('Error:', error);
});Explanation
axios.get(url)returns a Promise that resolves to aresponseobject.response.datacontains the parsed response body..catch()handles errors like network failures or HTTP errors.
Making a POST Request
axios.post('https://api.example.com/submit', {
name: 'Jane Doe',
age: 28
})
.then(response => {
console.log('Server Response:', response.data);
})
.catch(error => {
console.error('Error:', error);
});Key Points
- The second argument is the request body, automatically stringified as JSON.
- Headers like
Content-Type: application/jsonare set automatically.
Customizing Requests with Config
Axios supports an options object to customize requests.
axios({
method: 'get',
url: 'https://api.example.com/data',
headers: {
'Authorization': 'Bearer YOUR_TOKEN'
},
timeout: 5000
})
.then(response => console.log(response.data))
.catch(error => console.error('Error:', error));Important Config Options
method: HTTP method (GET, POST, PUT, DELETE, etc.).url: Endpoint URL.headers: Custom headers.params: Query string parameters.data: Request body (for POST, PUT).timeout: Time in ms before request is aborted.
Handling Errors
Axios distinguishes between different types of errors:
axios.get('https://api.example.com/invalid')
.then(response => console.log(response.data))
.catch(error => {
if (error.response) {
// Server responded with a status outside 2xx
console.error('Response error:', error.response.status, error.response.data);
} else if (error.request) {
// No response received
console.error('No response:', error.request);
} else {
// Other errors
console.error('Error setting up request:', error.message);
}
});Setting Base URL
Configure a default base URL to avoid repetition.
const api = axios.create({
baseURL: 'https://api.example.com',
timeout: 5000
});
api.get('/data')
.then(response => console.log(response.data));Using Interceptors
Interceptors let you modify requests or handle responses globally.
Request Interceptor
axios.interceptors.request.use(config => {
config.headers.Authorization = 'Bearer YOUR_TOKEN';
console.log('Request sent:', config);
return config;
}, error => {
return Promise.reject(error);
});Response Interceptor
axios.interceptors.response.use(response => {
console.log('Response received:', response);
return response;
}, error => {
console.error('Response error:', error.response ? error.response.status : 'Network Error');
return Promise.reject(error);
});Canceling a Request
Use CancelToken to cancel in-flight requests.
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:', error);
}
});
// Cancel after 2 seconds
setTimeout(() => {
source.cancel('Operation canceled by user.');
}, 2000);Uploading Files
const formData = new FormData();
formData.append('file', fileInput.files[0]);
axios.post('https://api.example.com/upload', formData, {
headers: {
'Content-Type': 'multipart/form-data'
}
})
.then(response => console.log('Upload success:', response.data))
.catch(error => console.error('Upload error:', error));Downloading Files
axios.get('https://api.example.com/file', {
responseType: 'blob'
})
.then(response => {
const url = window.URL.createObjectURL(new Blob([response.data]));
const link = document.createElement('a');
link.href = url;
link.setAttribute('download', 'file.pdf');
document.body.appendChild(link);
link.click();
});Best Practices
- Create an Axios instance for reusable configurations.
- Handle errors using
error.response,error.request. - Use interceptors for logging, authentication, or error handling globally.
- Apply timeouts and cancel tokens to prevent hanging requests.
- Stream large uploads and downloads using proper config.