Comparing Fetch API and Axios for HTTP Requests
Handling Cookies
When making same-origin requests, both fetch and axios automatically include cookies. For cross-origin scenarios, however, different configurations are required:
- Fetch: You must explicitly set the
credentialsoption to'include'in the configuration object. - Axios: You must set
withCredentials: truewithin the request configuration.
Using the Fetch API
fetch is built into modern browsers, reqiuring no additional dependencies. It returns a Promise and operates at a lower level, meaning developers must manually parse response bodies using methods like .json(), .text(), or .blob().
To manage request cancellation, utilize the AbortController interface:
const controller = new AbortController();
fetch('/api/data', {
method: 'GET',
signal: controller.signal
})
.then(response => {
if (!response.ok) throw new Error(`Status: ${response.status}`);
return response.json();
})
.then(data => console.log(data))
.catch(err => {
if (err.name === 'AbortError') {
console.log('Request aborted');
} else {
console.error('Fetch failed:', err);
}
});
// Trigger cancellation
controller.abort();
Using Axios
axios is a feature-rich, promise-based library that simplifies HTTP interactions at the cost of increasing bundle size. Key advantages include:
Concurrent Requests
Axios provides built-in utilities for executing multiple requests simultaneously:
import axios from 'axios';
async function fetchDashboardData() {
const [profile, settings] = await axios.all([
axios.get('/api/profile'),
axios.get('/api/settings')
]);
console.log('Profile:', profile.data);
console.log('Settings:', settings.data);
}
Automatic Serialization
Unlike fetch, which requires an explicit parsing step, axios automatically transforms JSON responses into objects.
// Axios handles JSON parsing automatically
axios.get('/api/config').then(res => console.log(res.data));
Request and Response Interceptors
Interceptors allow you to transform requetss or handle errors globally before they are passed to the application logic.
axios.interceptors.request.use(config => {
config.headers['Authorization'] = 'Bearer token';
return config;
}, err => Promise.reject(err));
axios.interceptors.response.use(res => res, err => {
if (err.response.status === 401) {
// Handle session expiry
}
return Promise.reject(err);
});
Request Cancellation
Axios supports the AbortController standard in newer versions, providing a consistent way to stop ongoing operations:
const controller = new AbortController();
axios.get('/api/long-task', {
signal: controller.signal
}).catch(err => {
if (axios.isCancel(err)) {
console.log('Request canceled by user');
}
});
controller.abort();