Home >Web Front-end >JS Tutorial >Axios and Fetch API? Choosing the Right HTTP Client
TL;DR: Axios and Fetch API are popular HTTP clients. Axios offers more features and easier error handling, while Fetch API is lightweight and native to browsers. Choose Axios for complex projects and Fetch for simpler ones
Two of the most common methods for handling asynchronous HTTP requests are fetch() and Axios. Despite being a common operation, the type of request you choose to work with can have a considerable influence on the usability and overall efficiency of an app. So, it is wise to thoroughly examine them and weigh their pros and cons before choosing one.
This article will compare these two widely used tools comprehensively to help you make the best choice for your project.
is a promise-based, third-party HTTP client commonly seen in browser ( XMLHttpRequests ) and Node.js (HTTP) environments. It provides a convenient API capable of intercepting requests and responses, performing request cancellations, and automatically parsing response data to JSON format. Axios also supports client-side protection against XSRF (cross-site request forgery). You can install Axios with a package manager like npm or add it to your project via a CDN.
// NPM npm install axios // CDN <script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
The Fetch API is also promise-based but a native JavaScript API available in all modern browsers. It is also compatible with Node.js environments and replaced the legacy XMLHttpRequests with a simpler and more contemporary approach. The Fetch API provides the fetch() method to send requests and supports multiple request and response types such as JSON, Blob, and FormData.
Since you now understand what Axios and fetch() are, let’s compare and contrast some key features of these two with code examples.
As far as syntax is concerned, Axios delivers a more compact and developer-friendly syntax than fetch().
Simple POST request with Axios:
// NPM npm install axios // CDN <script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
Similar POST request with fetch():
axios.post('https://jsonplaceholder.typicode.com/todos', { userId: 11, id: 201, title: "Try Axios POST", completed: true }) .then(response => { document.getElementById('output').innerHTML = ` <h2>Post Created:</h2> <p>Title: ${response.data.title}</p> <p>Completed status: ${response.data.completed}</p> `; }) .catch(error => { console.error('Error:', error); document.getElementById('output').innerHTML = '<p>Error creating post.</p>'; });
It is quite noticeable as even though fetch() is lightweight, it still requires more manual work to perform some common tasks. For instance, Axios comes with automatic JSON parsing and can directly access the data object of the response. In contrast, in fetch(), you have to parse the response to JSON format manually. Despite both presented approaches producing similar results, you have to explicitly handle the errors, serializations, and headers in fetch().
Handling errors is something that developers encounter almost every day. Axios, for instance, handles any HTTP call with a status code outside the 2xx range as an error by default. It gives you an explanatory object that is useful in managing and debugging your errors.
fetch('https://jsonplaceholder.typicode.com/todos', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ // Manually converting the object to JSON userId: 11, id: 202, title: 'Try Fetch POST', completed: true }) }) .then(response => { if (!response.ok) { // Manual error handling for HTTP errors throw new Error('Error creating post'); } return response.json(); // Manually parsing the response to JSON });
fetch() does not automatically treat HTTP errors (status codes 4xx or 5xx) as errors. You have to perform conditional checks manually to identify the response status to capture the error. But you can have custom error-handling logic within your project to gather information and handle errors as Axios does.
axios.get('https://jsonplaceholder.typicode.com/invalid_endpoint') .then(response => { console.log(response.data); }) .catch(error => { if (error.response) { // Server responded with a status outside of 2xx console.log('Error Status:', error.response.status); console.log('Error Data:', error.response.data); } else if (error.request) { console.log('Error Request:', error.request); } else { console.log('Error Message:', error.message); }});
If you need compatibility with legacy dependencies, such as an older browser like Internet Explorer (IE11) or older versions of most modern browsers, your go-to solution is Axios.
fetch() is native to modern browsers and functions seamlessly with them. However, it does not support some older browser versions. You can still use it with polyfills like whatwg-fetch to get it working in browsers that do not use fetch(). It is important to note that using polyfills might increase your bundle size and affect performance, though.
!(https://www.syncfusion.com/blogs/wp-content/uploads/2024/11/Fetch-compatibility.png)
HTTP interceptors allow the intercepting of requests and responses and come in handy when:
This powerful feature comes out of the box with Axios but is not natively supported by fetch().
Adding auth token to requests with Axios:
// NPM npm install axios // CDN <script src="https://cdn.jsdelivr.net/npm/axios@1.6.7/dist/axios.min.js"></script>
However, that does not mean fetch() cannot perform HTTP interception. You can use middleware to write a custom wrapper manually to mimic this behavior.
Adding auth token to requests with fetch() wrapper:
axios.post('https://jsonplaceholder.typicode.com/todos', { userId: 11, id: 201, title: "Try Axios POST", completed: true }) .then(response => { document.getElementById('output').innerHTML = ` <h2>Post Created:</h2> <p>Title: ${response.data.title}</p> <p>Completed status: ${response.data.completed}</p> `; }) .catch(error => { console.error('Error:', error); document.getElementById('output').innerHTML = '<p>Error creating post.</p>'; });
Response time-out refers to the time a client will wait for the server to respond. If this time limit is reached, the request is counted as unsuccessful. Axios and fetch() support request time-outs, essential when dealing with unreliable or slow networks. Still, Axios takes the lead by providing a more straightforward approach to time-out management.
A request time-out with Axios:
fetch('https://jsonplaceholder.typicode.com/todos', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ // Manually converting the object to JSON userId: 11, id: 202, title: 'Try Fetch POST', completed: true }) }) .then(response => { if (!response.ok) { // Manual error handling for HTTP errors throw new Error('Error creating post'); } return response.json(); // Manually parsing the response to JSON });
A request time-out with fetch():
axios.get('https://jsonplaceholder.typicode.com/invalid_endpoint') .then(response => { console.log(response.data); }) .catch(error => { if (error.response) { // Server responded with a status outside of 2xx console.log('Error Status:', error.response.status); console.log('Error Data:', error.response.data); } else if (error.request) { console.log('Error Request:', error.request); } else { console.log('Error Message:', error.message); }});
Axios handles the time-outs more simply and gracefully with cleaner code using its time-out option. But, fetch() needs manual timeout handling with AbortController(), which gives you more control over how and when the request is aborted.
For more details, refer to the complete examples for Axios vs. Fetch on the GitHub repository.
As with many tools, both Axios and Fetch API come with strengths and weaknesses. If you require automatic parsing of JSON, integrated error handling, and interceptors to streamline complicated processes, go with Axios. Choose fetch() if you want a pure and simple interface that is best suited for modern browser environments and does not require an external library. In short, both work well, but they are suited to different levels of complexity and functionality requirements.
The above is the detailed content of Axios and Fetch API? Choosing the Right HTTP Client. For more information, please follow other related articles on the PHP Chinese website!