Both Axios and Fetch are popular tools for making HTTP requests in JavaScript, but they have some key differences. Here’s a breakdown:
Axios
Built-in Features: Axios comes with many built-in features like automatic JSON transformation, request and response interceptors, and cancellation of requests.
Browser Compatibility: It supports older browsers, including Internet Explorer.
Error Handling: Axios automatically rejects promises for HTTP error statuses (like 404 or 500), making error handling simpler.
Request/Response Interceptors: You can easily modify requests or responses globally.
Cancel Requests: Axios provides an easy way to cancel requests.
Fetch
Native API: Fetch is a native web API, meaning you don’t need to install any additional libraries.
Promise-Based: It uses Promises, but you need to manually check the response status for errors.
Stream Handling: Fetch supports streaming, which can be useful for handling large responses.
More Control: You have more control over requests, but it requires more boilerplate code for features like setting defaults or intercepting requests.
No Built-in Support for JSON: You need to call .json() on the response object to parse JSON data.
Use Cases
Use Axios if you need a rich feature set out of the box, especially for complex applications.
Use Fetch for simpler use cases or when you want to avoid external dependencies.
Example Usage
Axios:
axios.get('/api/data')
.then(response => console.log(response.data))
.catch(error => console.error(error));
// axios
const options = {
url: 'http://localhost/test.htm',
method: 'POST',
headers: {
'Accept': 'application/json',
'Content-Type': 'application/json;charset=UTF-8'
},
data: {
a: 10,
b: 20
}
};
axios(options)
.then(response => {
console.log(response.status);
});
Now compare this code to the fetch() version, which produces the same result:
fetch('/api/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(error));
// fetch()
const url = "https://jsonplaceholder.typicode.com/todos";
const options = {
method: "POST",
headers: {
Accept: "application/json",
"Content-Type": "application/json;charset=UTF-8",
},
body: JSON.stringify({
a: 10,
b: 20,
}),
};
fetch(url, options)
.then((response) => response.json())
.then((data) => {
console.log(data);
});
Notice that:
To send data, fetch() uses the body property for a post request to send data to the endpoint, while Axios uses the data property
The data in fetch() is transformed to a string using the JSON.stringify method
Axios automatically transforms the data returned from the server, but with fetch() you have to call the response.json method to parse the data to a JavaScript object
With Axios, the data response provided by the server can be accessed within the data object, while for the fetch() method, the final data can be named any variable
Conclusion
Both have their strengths, and the choice often comes down to your specific needs and preferences. If you're building a larger application with many API interactions, Axios might save you some hassle, while Fetch is great for straightforward tasks.
Axios offers a user-friendly API that simplifies most HTTP communication tasks. However, if you prefer using native browser features, you can definitely implement similar functionalities yourself with the Fetch API.
As we've explored, it’s entirely feasible to replicate the essential features of Axios using the fetch()
method available in web browsers. The decision to include a client HTTP library ultimately depends on your comfort level with native APIs and your specific project requirements.
For more information: https://blog.logrocket.com/axios-vs-fetch-best-http-requests/
Top comments (43)
I don't understand the fixation of people with
axios
. It should just be a legacy package. This is no longer needed. Just go with a customized function that usesfetch
. The customized function can replace all interception needs. Far simpler and no package dependencies.Same, I just use fetch and if I need some sort of shared behavior I write a little wrapper around it. That's usually much simpler and more understandable even if it requires 2-3 extra lines of code compared to an axios equivalent.
That's another thing: It is like 10 lines of code to just add an interceptor to axios. It is more lines of code most of the time.
Me neither haha, but there are companies that still use.
This would be a good opportunity to eventually refactor, remove Axios, and reduce the bundle size of the company's repository.
Simple 😂😂😂
I really love the semi-knowledge in our industry reflected by some of the comments.
fetch
also provides a very simple (and standard) way to abort requests - using a genericAbortController
fetch
I don't get why people are so extreme. Yes, you should prefer using
fetch
. No, somebody who uses Axios might still have a valid case - so stop burning people / their choices and embrace that we have options.UPload progress is now possible with fetch. There's a package that allows this. This is possible now because of stream support recently added to browsers.
I think the only valid reason for
axios
is to cover old browsers that don't providefetch
. Therefore,axios
itself should now be legacy.Hm which package do you mean? I only know npmjs.com/package/fetch-progress and this is for download progress. Surely, you can also add upload progress via a
ReadableStream
- but that's essentially my point: It's not supported out of the box fromfetch
(e.g., via a progress event) - so you need to write more code / use some package to get the functionality.axios
adds a couple of things on top - now, personally I don't need them, but if you want those extra things then there is certainly nothing wrong with usingaxios
.Only a sith deals in absolutes - always be open minded!
Nope. This one.
I wouldn't download the entirety of legacy
axios
just for upload progress. I'd use the more modern package and that's it. Even iffetch
doesn't provide it as a stock option, that's no justification to continue using something that should just be archived.My feeling is that you either have not read or not understood what I wrote. I may have a problem communicating well here - so I take the blame.
If you carefully read what I wrote you'll find
among other things.
"many others"? Care to enumerate? Because that's my point. There is probably so little to enumerate that
axios
shouldn't be worth under any circumstances, as more modern packages, that are more focused and less bulky, can do.Hello ! Don't hesitate to put colors on your
codeblock
like this example for have to have a better understanding of your code 😎Thanks for letting me know, but he was sure I had done this before, I probably didn't save it haha
Glad I helped you rethink that, an article with colored code, is easier to read and improves reading! 😎
Axios is good when you need to support old browsers, since it uses XHR under the hood. But from the other hand it slower than fetch API, I would recommend to use ky, it has same features like req, res interception and automatically rejection HTTP errors by status. Ky is using fetch as base so it faster.
I love the fact that the JavaScript ecosystem is progressively adopting the same Web Standards APIs in both browsers and Node runtimes. It makes development experience so much nicer.
The only thing I regret about
fetch
compared toaxios
, is that HTTP status >= 400 are not considered as errors, and don't throw/reject, which is really painful when trying to implement a clean errors handling system.To overcome that issue, I've implemented a small wrapper around
fetch
, that reproduces axios behaviour.A status code outside the range [200..300[ should not be a runtime error. This is some invention that came to be. This forces you to program logic using exceptions, which is a bad practice. The correct way to code is to use branching (IF or switch).
Bro it's 2024, there absolutely no use case for axios! Abolish this thing already!!
LOL I take it you haven't had to try and support progress indicators in an app recently. Fetch still doesn't support it. Have to fall back to XHR, which axios is built on and makes nicer.
There are use cases sadly since they didn't bother making fetch have feature parity with XMLHttpRequest
So while you don't need axios any more than you ever did, there are still valid use cases for it when you don't want to waste time reinventing the wheel just to save a dependency.
LOL.
So you're bringing in all that bloat for what? Progress events? Seriously, bro, just stick with XHR for that one case. There's no excuse for pulling Axios into your app when you can do the job without dragging in 30kb of overhead. Stop overcomplicating..
Progress already possible with
fetch
.I see , but students still understand this, in addition, some back end systems use it, but of course it depends on the company, I prefer fetch , I think it's easier and more satisfying to use it.
I use Axios for interceptors feature which afaik fetch doesn’t have.
Sure I could build my own, but then I’d have to build my own
The AI says this is what is needed to inject a token with an
axios
interceptor:This is code you must write.
If you simply write a custom fetching function, the same is something like:
And interception of responses is as easy. So
axios
is more work than plainfetch
.Nice! Thanks!
I've been using fetch api since I've learned about 5 years ago I think since I don't want to add external modules such as axios. There could be more native JavaScript API nowadays so Id really like to use that as well
Nice read. I wrote a similar article for those interested. Link here.
Excellent presentation! very concise!
Good work!
Some comments may only be visible to logged-in visitors. Sign in to view all comments.