Introduction
Earlier this year when i worked as an Instructor in a bootcamp teaching Full-Stack Software Engineering, a student asked why i used axios in one of my tutorials. This post was my response. He suggested I posted it online to help others because he found it helpful (I added more content to the original response).
Plus, this is me trying to be productive since i couldn't record any content for my YouTube Channel this week.
The Basics
Firstly, axios and fetch are both for handling http request and both of them returns a Promise.
So, they can both be used with async-await since async-await is just syntactic sugar for handling a Promise instead of using then-catch blocks.
axios is an alternative to fetch. fetch is the default http client that comes with your browsers for handling http requests.
Some advantages of axios over fetch
axios is a 3rd party npm package you have to install and it has some advantages which we would discuss in this post.
Default JSON parsing
One of the most visible one from the movie search app is that you don't have to call res.json() on the response when using axios (unlike fetch) because axios handles that for you automatically. Meaning that axios parses the response to JSON by default.
// Using fetch
async function loadUserFetch() {
try{
const response = await fetch("https://jsonplaceholder.typicode.com/users/1")
const data = await response.json(); // Manually Parse JSON
console.log(data)
}catch(error) {
console.log(error.message)
}
}
// Using axios
async function loadUserAxios() {
try{
const response = await axios.get("https://jsonplaceholder.typicode.com/users/1")
console.log(response.data) // Already parsed by axios
}catch(error) {
console.log(error.message)
}
}
O wow!! That's cool. So i just saved one line of code? Whew! Thanks.
Well the fetch code could be written in one line, like so:
const data = await (await fetch("https://jsonplaceholder.typicode.com/users/1")).json()
console.log(data)
The main point to note is not the extra line that axios saves you from but the fact that axios parses the returned response by default.
axios works inside and outside a browser's window
Wait, let me explain what i mean by this.
fetch can only work inside a browser.
Why is that so?
Well, fetch is a method of the window object that is: window.fetch().
The window object has lots of cool methods and properties that adds more functionality and lets you do some cool stuffs with Javascript inside your browser. Some other methods of the window object are alert(), confirm(), etc.
Remember! Javascript runs only inside the browser by default. So your browser is the default runtime environment for your Javascript code.
Node.js makes Javascript run outside the browser (which makes it a runtime environment for Javascript).
Since fetch belongs to the window object which is part of your browser's environment, fetch can't work in a Node.js environment because it has no browser window to operate on.
What can i do about this?
Well you could use a Node.js based http client library like axios, superagent, node-fetch, isomorphic-unfetch et al.
Axios can work in the browser and in a Node.js environment.
With this, your Node.js powered applications now have the power to make http request.
Wait! What? So you mean Node.js doesn't have a http module or something to handle http request?
Node.js definately has the http and https modules that handles http request but they are fairly low-leveled and you'll have to receive the response in chunks and track when its done. Plus, you'll have to parse your data to JSON manually too.
Last but not the least, they don't come with the goodness of Promises.
Handy request method aliases
Another advantage is the handy http request methods(get, post, etc) aliases that comes with axios.
Just like in the user search, i used axios.get(...) it also has axios.post(...) and others.
If i want to perform a post request using fetch, i'll have to do something like this:
// Using fetch
async function createUser() {
const response = await fetch('https://httpbin.org/post', {
method: 'POST',
body: JSON.stringify({ name: 'John', email: 'john@mail.com' })
});
}
But with axios, i'll do:
// Using axios
async function createUser() {
const response = await axios.post('https://httpbin.org/post', { name: 'John', email: 'john@mail.com' });
}
Axios lets you intercept requests/response and cancel request
Axios lets you easily intercept between a request and response.
This is a bit more advanced but what that simply means is that you could intercept a response before it reaches its destination and do something (eg. if it the request returns an error, you could immediately redirect or set a state based on the error).
With time you'll get to see the use-cases and know when you apply them. Learn more.
Finally, axios provides a simple API that lets you cancel requests.
Modern browsers have started implementing an experimental feature to let you abort fetch requests. As of the time of this writing, it is currently an experimental technology.
Summary
Axios simply provides us with a cleaner and simpler API to handle http requests both in our browser and in Node.js based applications. You must not use axios or any third party library in your browser based applications but we saw that you'll need a third party library like axios (or any other one which you prefer) for your Node.js based applications.
If you were observant to details, you'll see that fetch() and other window methods like alert() are not part of Javascript as a language according to the ECMAScript specification. Instead, they're are just bunch of add-ons provided and implemented by browsers.
I don't believe you!! This doesn't sound right.
Yes, it's okay not to believe because we were all taught about alert() et al while learning Javascript.
Well, i got some exercises for you:
- Okay, if
fetchis part of Javascript, why can't you use it in your Node.js apps? Try it. - Try this:
alert("Hello World")in any Node.js app.
Since this article isn't about how Javascript works, we would not be going into that.
There are other advantages which you can discover as you start using this library for your applications. You could read the axios doc docs for more information.
I hope this article was helpful.
Thanks for reading.
All the best
Oldest comments (21)
I often use isomorphic-unfetch myself, it's a good choice
Thanks so much for the feedback.
I did not forget to add isomorphic-unfetch.
I just didn't know about it yet. Lol...
About the open issues, react and flutter has 600+ and 5000+ open issues respectively.
Measuring the awesomeness of a library or framework by using only open issues and PRs alone is not a good yardstick. You need to include other variables to your analysis to draw a conclusion that is more precise and reflects the opinion of the community using the said library or framework.
Thanks for the feedback once again and i have mentioned isomorphic-unfetch in the article. But you'll be the one replying to any question related to that library in the comment section ;)
There is also the request package (npmjs.com/package/request), although for Node only. It has 15M downloads weekly while Axios has 5M only.
I'm in trouble. The list never ends :(
I use the isomorphic-unfetch too, i think axios is like a "nice to have" but it isn't the most useful library.
unfetch used only by 50k
"superagent" lib used by 250k and it much more maintained
Great article! I came across axios a while back, but enjoyed the read and clarifying points. Appreciate the write up!
I'm glad you liked it.
Error handling is very nicely done in axios too. With fetch lots of if statements for simple error handling.
Ah this is true. I intended adding that to the article but forgot.
Yeah. fetch throws for only network errors and you'll have to manually check for other errors unlike axios.
Guess I'll have to add this to the article with an example.
Thanks for sharing
The other thing that I've found that
axioscan do that I couldn't getfetchto do correctly was to properly save a cookie to use for post requests over https (I think that was the issue) in a React Native application. It's been awhile, so I don't 100% remember the specifics - but I remember thataxiosworked whenfetchdidn't.Thanks for the post!
Ah nice.
You're welcome
One nice thing about axios is the pre/post request hooks. You could use them for say add authentication tokens and globally handle request errors.
Enjoyed the article, thank you for sharing πIn addition to this list, I find the biggest advantage of axios is that it is using XHR internally, meaning we can get updates on request progress ποΈ(onUploadProgress and onDownloadProgress).
Didn't know that until now. Thanks for sharing..
Thanks for the feedbacks.
Would update the article by Monday with examples to show more differences between the two.
More ideas are coming in :)
Very nice and informative article.
Thanks a lot.