乐闻世界logo
搜索文章和话题

What are the differences between axios and fetch API? In what scenarios should axios be chosen?

3月6日 23:04

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

FeatureAxiosFetch API
API DesignPromise-based, more friendly APINative Promise, lower-level API
JSON ProcessingAutomatic JSON data conversionRequires 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 HandlingHTTP errors auto rejectOnly network errors reject
Browser CompatibilityIE11+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):

javascript
try { 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):

javascript
const 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):

javascript
axios.get('/api/data', { timeout: 5000 // 5 second timeout });

Fetch (Manual Implementation Required):

javascript
const 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):

javascript
axios.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

  1. Need Interceptor Functionality

    • Unified authentication Token addition
    • Unified error handling
    • Unified logging
  2. Need Progress Monitoring

    • File upload/download
    • Large file transfer
  3. Need Timeout Control

    • Prevent request hanging
    • Improve user experience
  4. High Project Complexity

    • Multiple API services
    • Complex error handling logic
    • Need request retry mechanism
  5. Need IE Support

    • Need to support IE11
  6. Node.js Environment

    • Server-side rendering
    • Node.js scripts

Scenarios for Using Fetch

  1. Pursuing Minimum Bundle Size

    • Projects sensitive to bundle size
    • Simple single-page applications
  2. Modern Browser Environment

    • No IE support needed
    • Modern frameworks (Next.js, Remix, etc.)
  3. Simple HTTP Requests

    • No complex interceptors needed
    • Simple GET/POST requests
  4. 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

ScenarioRecommended Tool
Enterprise applicationsAxios
Need interceptorsAxios
File upload/downloadAxios
Need timeout controlAxios
Need IE supportAxios
Node.js environmentAxios
Simple projectsFetch
Size sensitiveFetch
Modern browsersFetch
Learning purposesFetch

General Recommendations:

  • Medium to large projects, need complex HTTP handling → Choose Axios
  • Small projects, simple requests, pursue lightweight → Choose Fetch
标签:JavaScript前端Axios