Fetch API vs Axios: A Comparison
When working with JavaScript for making HTTP requests, two popular tools are Fetch API and Axios. Both serve the same purpose—making requests to APIs or servers—but they have different features, syntax, and behaviors. In this article, we will compare the two based on different factors to help you decide which one is the best choice for your project.
1. Overview
Fetch API
The Fetch API is a built-in JavaScript API that allows you to make network requests similar to XMLHttpRequest
. It’s built into modern browsers and returns Promises, making it easy to work with asynchronous code.
Example of using Fetch:
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.log(error));
Axios
Axios is a promise-based HTTP client for the browser and Node.js. It provides an easy-to-use API for making requests and is popular in the React ecosystem due to its simplicity and additional features over the Fetch API.
Example of using Axios:
import axios from 'axios';
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.log(error));
2. Browser Support
- Fetch API: The Fetch API is supported in all modern browsers (Chrome, Firefox, Safari, Edge). However, it is not supported in Internet Explorer.
- Axios: Axios works across all browsers, including Internet Explorer 11. It provides more extensive support across various environments, including older browsers.
3. Syntax and Ease of Use
Fetch API
The Fetch API uses Promises, so the syntax is clean and modern, but there are some nuances you need to handle (e.g., checking response status or parsing JSON).
Example:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('Network response was not ok');
}
return response.json();
})
.then(data => console.log(data))
.catch(error => console.error('There was a problem with the fetch operation:', error));
Axios
Axios simplifies working with HTTP requests and handles some things automatically (such as parsing JSON, error handling, and status codes). This makes it a bit more user-friendly.
Example:
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
4. Handling JSON
Fetch API: The Fetch API does not automatically parse the response as JSON. You need to manually call
response.json()
to parse it.Axios: Axios automatically parses the JSON response, so you don’t need to explicitly use
response.json()
.
5. Handling Errors
-
Fetch API: Fetch does not reject the promise on HTTP errors (such as 404 or 500). Instead, it resolves the promise, and you have to check
response.ok
to determine if the request was successful or not.
Example:
fetch('https://api.example.com/data')
.then(response => {
if (!response.ok) {
throw new Error('HTTP error!');
}
return response.json();
})
.catch(error => console.log(error));
-
Axios: Axios automatically rejects the promise for HTTP error status codes (404, 500, etc.), so you can directly handle errors in the
.catch()
block without having to check the status manually.
Example:
axios.get('https://api.example.com/data')
.then(response => console.log(response.data))
.catch(error => console.log(error)); // error is automatically caught for HTTP errors
6. Request and Response Interceptors
Fetch API: The Fetch API doesn’t have built-in support for request or response interceptors. You would need to manually create these using middleware-like patterns.
Axios: Axios provides built-in support for request and response interceptors, which makes it easy to modify requests or responses globally before the request is sent or after the response is received. This is especially useful for adding authentication tokens or logging.
Example of using Axios interceptors:
axios.interceptors.request.use(request => {
console.log('Request sent at:', new Date());
return request;
});
axios.interceptors.response.use(response => {
console.log('Response received at:', new Date());
return response;
});
7. Handling Timeouts
-
Fetch API: The Fetch API doesn’t have built-in support for timeouts. You would need to manually implement timeout logic using
AbortController
.
Example:
const controller = new AbortController();
const timeoutId = setTimeout(() => controller.abort(), 5000);
fetch('https://api.example.com/data', { signal: controller.signal })
.then(response => response.json())
.then(data => console.log(data))
.catch(error => {
if (error.name === 'AbortError') {
console.log('Request timed out');
} else {
console.error(error);
}
});
- Axios: Axios has built-in support for timeouts, and you can specify a timeout when making a request.
Example:
axios.get('https://api.example.com/data', { timeout: 5000 })
.then(response => console.log(response.data))
.catch(error => {
if (error.code === 'ECONNABORTED') {
console.log('Request timed out');
} else {
console.error(error);
}
});
8. Request Cancellation
Fetch API: The Fetch API supports request cancellation using
AbortController
, as demonstrated above.Axios: Axios supports request cancellation via the
CancelToken
API, which allows you to cancel an ongoing request easily.
Example:
const source = axios.CancelToken.source();
axios.get('https://api.example.com/data', {
cancelToken: source.token
}).then(response => console.log(response.data))
.catch(error => {
if (axios.isCancel(error)) {
console.log('Request canceled', error.message);
} else {
console.error(error);
}
});
// To cancel the request
source.cancel('Operation canceled by the user.');
9. File Uploads and Downloads
- Fetch API: You can use the Fetch API to upload files, but you will need to handle file creation and multipart form data manually.
Example:
const formData = new FormData();
formData.append('file', fileInput.files[0]);
fetch('https://api.example.com/upload', {
method: 'POST',
body: formData
})
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error uploading file:', error));
- Axios: Axios makes it easier to send files with automatic handling of multipart form data.
Example:
const formData = new FormData();
formData.append('file', fileInput.files[0]);
axios.post('https://api.example.com/upload', formData)
.then(response => console.log(response.data))
.catch(error => console.error('Error uploading file:', error));
10. Summary Comparison
Feature | Fetch API | Axios |
---|---|---|
Browser Support | Modern browsers (no IE support) | All browsers (including IE) |
Error Handling | Must check response status manually | Automatically handles HTTP errors |
JSON Parsing | Manual parsing (response.json() ) |
Automatically parses JSON |
Request Interceptors | No support | Built-in support |
Response Interceptors | No support | Built-in support |
Timeouts | Manual with AbortController
|
Built-in support |
Request Cancellation | Manual with AbortController
|
Built-in support with CancelToken
|
File Uploads | Requires manual form data handling | Built-in support for file uploads |
Conclusion
Use Fetch API if you prefer a native, lightweight solution for making HTTP requests and are okay with manually handling some aspects like error handling, JSON parsing, and timeouts.
Use Axios if you need a feature-rich, user-friendly solution that simplifies working with requests and responses, has built-in support for interceptors, handles timeouts and cancellations more easily, and provides cross-browser support (including IE).
Top comments (0)