What is axios
Axios is a Promise-based HTTP client that works in both browser and Node.js environments. It provides a clean API for handling HTTP requests and responses.
Advantages of Axios over Fetch API
1. Automatic JSON Transformation
javascript// Axios automatically handles JSON const response = await axios.get('/api/users'); console.log(response.data); // Already a JavaScript object // Fetch requires manual conversion const response = await fetch('/api/users'); const data = await response.json(); // Requires additional call
2. Request/Response Interceptors
javascript// Add request interceptor axios.interceptors.request.use(config => { config.headers.Authorization = `Bearer ${token}`; return config; }); // Add response interceptor axios.interceptors.response.use( response => response, error => { if (error.response.status === 401) { // Handle unauthorized } return Promise.reject(error); } );
3. Request Cancellation
javascriptconst controller = new AbortController(); axios.get('/api/data', { signal: controller.signal }); // Cancel request controller.abort();
4. Better Error Handling
- Axios automatically rejects Promise on HTTP error status codes (4xx, 5xx)
- Provides more detailed error information (response, request, config, etc.)
5. Request Timeout
javascriptaxios.get('/api/data', { timeout: 5000 });
6. Progress Monitoring Support
javascriptaxios.post('/api/upload', formData, { onUploadProgress: (progressEvent) => { const percentCompleted = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); } });
7. Browser and Node.js Compatibility
- Browser side based on XMLHttpRequest
- Node.js side based on http module
8. CSRF Protection Support
javascriptaxios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken';
Summary
| Feature | Axios | Fetch API |
|---|---|---|
| Auto JSON Transform | ✅ | ❌ |
| Interceptors | ✅ | ❌ |
| Request Cancellation | ✅ | ✅ (AbortController) |
| Timeout Setting | ✅ | ❌ |
| Progress Monitoring | ✅ | ❌ |
| Browser Compatibility | IE11+ | Modern browsers |
| Bundle Size | ~13KB | Native support |
Axios is suitable for scenarios requiring complex HTTP handling, while Fetch API is suitable for simple request scenarios.