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

What is axios and what are its advantages compared to the native fetch API?

3月6日 21:56

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

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

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

6. Progress Monitoring Support

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

javascript
axios.defaults.xsrfCookieName = 'csrftoken'; axios.defaults.xsrfHeaderName = 'X-CSRFToken';

Summary

FeatureAxiosFetch API
Auto JSON Transform
Interceptors
Request Cancellation✅ (AbortController)
Timeout Setting
Progress Monitoring
Browser CompatibilityIE11+Modern browsers
Bundle Size~13KBNative support

Axios is suitable for scenarios requiring complex HTTP handling, while Fetch API is suitable for simple request scenarios.

标签:JavaScript前端Axios