When building web apps, you often need to fetch data from APIs or send data to a server. In JavaScript, two popular ways to make HTTP requests are Fetch API and Axios. But which one should you use? In this guide, we’ll break it down with examples, pros and cons, features, and real-life use cases.
๐ What is Fetch API?
Fetch API is a built-in browser feature that allows you to make HTTP requests. It returns Promises and is supported in all modern browsers.
fetch('https://jsonplaceholder.typicode.com/posts') .then(response => response.json()) .then(data => console.log(data)) .catch(error => console.error(error));
⚙️ What is Axios?
Axios is a third-party JavaScript library built on top of XMLHttpRequest
. It provides a clean API for sending HTTP requests and handling responses.
axios.get('https://jsonplaceholder.typicode.com/posts') .then(response => console.log(response.data)) .catch(error => console.error(error));
๐ Syntax Comparison
POST Request
// Fetch fetch('/api/user', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ name: 'John' }) }) .then(res => res.json()) .then(data => console.log(data)); // Axios axios.post('/api/user', { name: 'John' }) .then(res => console.log(res.data));
๐ Feature Comparison Table
Feature | Fetch | Axios |
---|---|---|
Built-in | Yes | No (needs install) |
JSON Auto Parsing | No | Yes |
Request Cancellation | AbortController | axios.CancelToken |
Request Timeout | No | Yes |
Interceptors | No | Yes |
Node.js Support | Yes (with node-fetch) | Yes |
Response Schema | Basic | Rich (status, headers, config) |
✅ Pros and Cons
Axios Pros
- Easy syntax
- Built-in JSON parsing
- Timeout support
- Interceptors for auth headers
Axios Cons
- Extra dependency
- Heavier bundle size
Fetch Pros
- No installation required
- Lightweight
- More control
Fetch Cons
- Verbose error handling
- No timeout or interceptors by default
๐ซ Error Handling Difference
Fetch does not throw on HTTP errors (like 404), while Axios does.
// Fetch fetch('/api') .then(res => { if (!res.ok) throw new Error('Failed'); return res.json(); }) .catch(err => console.error(err)); // Axios axios.get('/api') .then(res => console.log(res.data)) .catch(err => console.error(err));
๐งพ JSON Handling
With Fetch, you must manually call res.json()
. Axios auto-converts JSON.
๐ค File Upload Example
// Using Axios const formData = new FormData(); formData.append('file', fileInput.files[0]); axios.post('/upload', formData) .then(res => console.log(res));
๐ Canceling Requests
// Axios cancel token const CancelToken = axios.CancelToken; const source = CancelToken.source(); axios.get('/data', { cancelToken: source.token }) .catch(thrown => { if (axios.isCancel(thrown)) { console.log('Request canceled', thrown.message); } }); source.cancel('Operation canceled by the user.');
๐งฉ Interceptors in Axios
Used to attach tokens, log requests, or modify headers globally.
axios.interceptors.request.use(config => { config.headers.Authorization = 'Bearer token'; return config; });
๐ Performance
Fetch is slightly faster due to being native and lighter. Axios may add milliseconds due to extra parsing and features.
๐ฏ When to Use What
- Use Fetch: Small apps, fewer dependencies, full control
- Use Axios: Complex apps, interceptors, automatic parsing
๐ Final Verdict
If you want simplicity and zero config, go with Fetch. If you prefer developer comfort, advanced features, and clean syntax — Axios is a great choice.
Thanks for reading! Let me know in the comments — are you Team Axios or Team Fetch?
Happy coding! ๐ง ๐ก
Comments
Post a Comment