Axios vs Fetch API Comparison
Both Axios and Fetch API are tools for sending HTTP requests, but they have significant differences in functionality, ease of use, and compatibility.
Core Differences Comparison Table
| Feature | Axios | Fetch API |
|---|---|---|
| API Design | Promise-based, more friendly API | Native Promise, lower-level API |
| JSON Processing | Automatic JSON data conversion | Requires manual .json() call |
| Request Interceptors | ✅ Native support | ❌ Requires custom wrapper |
| Response Interceptors | ✅ Native support | ❌ Requires custom wrapper |
| Request Cancellation | ✅ Supports AbortController | ✅ Supports AbortController |
| Timeout Setting | ✅ Native timeout support | ❌ Requires manual implementation |
| Progress Monitoring | ✅ Native onUploadProgress/onDownloadProgress | ❌ Requires manual implementation |
| Error Handling | HTTP errors auto reject | Only network errors reject |
| Browser Compatibility | IE11+ | Chrome 42+, Edge 14+, Firefox 39+ |
| Bundle Size | ~13KB (gzip) | Native support, no extra size |
| Node.js Support | ✅ Supported | ❌ Not supported (needs polyfill) |
Detailed Comparison Analysis
1. JSON Data Processing
Axios (Automatic):
javascript// Automatically converts response to JSON const response = await axios.get('/api/users'); console.log(response.data); // Already a JavaScript object // Automatically converts request body to JSON await axios.post('/api/users', { name: 'John' });
Fetch (Manual):
javascript// Need to manually call .json() const response = await fetch('/api/users'); const data = await response.json(); // Additional await console.log(data); // Need to manually set headers and stringify await fetch('/api/users', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John' }) });
2. Error Handling
Axios (Automatic HTTP Error Handling):
javascripttry { const response = await axios.get('/api/not-found'); } catch (error) { // 404 will enter catch console.log(error.response.status); // 404 }
Fetch (Manual Status Check Required):
javascriptconst response = await fetch('/api/not-found'); // Need to manually check status code if (!response.ok) { // 404 won't automatically enter catch throw new Error(`HTTP error! status: ${response.status}`); }
3. Timeout Setting
Axios (Native Support):
javascriptaxios.get('/api/data', { timeout: 5000 // 5 second timeout });
Fetch (Manual Implementation Required):
javascriptconst fetchWithTimeout = (url, options = {}, timeout = 5000) => { return Promise.race([ fetch(url, options), new Promise((_, reject) => setTimeout(() => reject(new Error('Request timeout')), timeout) ) ]); };
4. Interceptors
Axios (Native Support):
javascript// Request interceptor axios.interceptors.request.use(config => { config.headers.Authorization = `Bearer ${token}`; return config; }); // Response interceptor axios.interceptors.response.use( response => response.data, error => { if (error.response.status === 401) { redirectToLogin(); } return Promise.reject(error); } );
Fetch (Custom Wrapper Required):
javascript// Need to create wrapper function const fetchWithAuth = (url, options = {}) => { return fetch(url, { ...options, headers: { ...options.headers, 'Authorization': `Bearer ${token}` } }); };
5. Progress Monitoring
Axios (Native Support):
javascriptaxios.post('/api/upload', formData, { onUploadProgress: (progressEvent) => { const percent = Math.round( (progressEvent.loaded * 100) / progressEvent.total ); console.log(`Upload progress: ${percent}%`); } });
Fetch (Manual Implementation Required):
javascript// Fetch has no native progress support, need to use ReadableStream const response = await fetch('/api/download'); const reader = response.body.getReader(); while (true) { const { done, value } = await reader.read(); if (done) break; // Manually calculate progress }
Selection Recommendations
Scenarios for Using Axios
-
Need Interceptor Functionality
- Unified authentication Token addition
- Unified error handling
- Unified logging
-
Need Progress Monitoring
- File upload/download
- Large file transfer
-
Need Timeout Control
- Prevent request hanging
- Improve user experience
-
High Project Complexity
- Multiple API services
- Complex error handling logic
- Need request retry mechanism
-
Need IE Support
- Need to support IE11
-
Node.js Environment
- Server-side rendering
- Node.js scripts
Scenarios for Using Fetch
-
Pursuing Minimum Bundle Size
- Projects sensitive to bundle size
- Simple single-page applications
-
Modern Browser Environment
- No IE support needed
- Modern frameworks (Next.js, Remix, etc.)
-
Simple HTTP Requests
- No complex interceptors needed
- Simple GET/POST requests
-
Learning Purposes
- Understanding underlying HTTP API
- Teaching demonstrations
Selection in Modern Frameworks
React/Vue/Angular Projects
javascript// Recommended to use Axios import axios from 'axios'; const api = axios.create({ baseURL: process.env.VUE_APP_API_URL, timeout: 10000 }); // Add interceptors api.interceptors.request.use(config => { const token = localStorage.getItem('token'); if (token) { config.headers.Authorization = `Bearer ${token}`; } return config; });
Next.js / Remix Projects
javascript// Can use Fetch (with framework data fetching functions) // app/page.js (Next.js App Router) async function getData() { const res = await fetch('https://api.example.com/data', { next: { revalidate: 3600 } // Cache configuration }); if (!res.ok) { throw new Error('Failed to fetch'); } return res.json(); }
Summary
| Scenario | Recommended Tool |
|---|---|
| Enterprise applications | Axios |
| Need interceptors | Axios |
| File upload/download | Axios |
| Need timeout control | Axios |
| Need IE support | Axios |
| Node.js environment | Axios |
| Simple projects | Fetch |
| Size sensitive | Fetch |
| Modern browsers | Fetch |
| Learning purposes | Fetch |
General Recommendations:
- Medium to large projects, need complex HTTP handling → Choose Axios
- Small projects, simple requests, pursue lightweight → Choose Fetch