DEV Community

Emmanuel Okiche
Emmanuel Okiche

Posted on • Edited on

When do you need axios?

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 fetch is 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

Top comments (21)

Collapse
 
fleepgeek profile image
Emmanuel Okiche

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 ;)

Collapse
 
krizpoon profile image
Kriz Poon • Edited

There is also the request package (npmjs.com/package/request), although for Node only. It has 15M downloads weekly while Axios has 5M only.

Thread Thread
 
fleepgeek profile image
Emmanuel Okiche

I'm in trouble. The list never ends :(

Collapse
 
gypsydave5 profile image
David Wickes

Oddly enough I always bring up axios when I want to talk about how not to write an HTTP client. I think a lot of the decisions around the design of its API make it harder to use in the long run. Two examples:

  1. Conflating network errors with valid HTTP responses. While it's initially easier to use, I've found it inevitably leads to confusion about what the source of an 'error' is. I much prefer the explicit handling of different HTTP responses (including 4xx and 5xx) that the fetch api encourages.

  2. What happens when the auto-parsing of JSON fails: nothing. Axios will swallow the error and leave you trying to access properties on a string that don't exist. Extremely hard to debug. The owner recognises the problem but has no solution

With axios we gain some convenience but at the expense of control and transparency. What we have to ask is whether it is worth the trade. Is the removal of a single method call to parse JSON worth the time it will take to work out what's going wrong when it (inevitably) does go wrong? Is the convenience of throwing on a 404 worth the pain of reconfiguring the client so that it doesn't throw on a 404 when I'm expecting a 404 response?

I prefer simple but verbose in the style of fetch; everyone has to make their own mind up.

Collapse
 
fleepgeek profile image
Emmanuel Okiche • Edited

Thanks for the feedback.
You have made a clear case with some strong points.
I learnt from your comment and i appreciate it.

Every library has its downsides and tradeoffs. You just have to choose what you can manage and which gets the job done.

Axios shines in terms of convenience and has a simpler API. This might be what a developer wants at some point. The issue link you shared definitely has some workarounds. No library is perfect. I absolutely get your point and you passed your message in a very clear and consise way. I respect that.

This article was just a way to show beginners why thousands of articles and tutorials use third party libraries like axios for node.js based projects. Most articles don't tell them why.

Ahh...lastly, i would update the article with my conclusion. Wrote this article at midnight so i missed that.

Thanks once again David

Collapse
 
samit4me profile image
Samuel Sharpe • Edited

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).

Collapse
 
pavindulakshan profile image
Pavindu Lakshan

Didn't know that until now. Thanks for sharing..

Collapse
 
chrisachard profile image
Chris Achard

The other thing that I've found that axios can do that I couldn't get fetch to 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 that axios worked when fetch didn't.

Thanks for the post!

Collapse
 
fleepgeek profile image
Emmanuel Okiche

Ah nice.
You're welcome

Collapse
 
vit1 profile image
Vitaly Pinchuk • Edited

this means axios is not maintained.

Totally agree! Axios loooks like is not maintained.

Collapse
 
fleepgeek profile image
Emmanuel Okiche

Thanks for the feedbacks.
Would update the article by Monday with examples to show more differences between the two.
More ideas are coming in :)

Collapse
 
bbarbour profile image
Brian Barbour

I often use isomorphic-unfetch myself, it's a good choice

Collapse
 
shubhambattoo profile image
Shubham Battoo

Error handling is very nicely done in axios too. With fetch lots of if statements for simple error handling.

Collapse
 
fleepgeek profile image
Emmanuel Okiche

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

Collapse
 
abbiranjan profile image
Alok Ranjan

Very nice and informative article.
Thanks a lot.

Collapse
 
ogaston profile image
Omar Gaston Chalas

I use the isomorphic-unfetch too, i think axios is like a "nice to have" but it isn't the most useful library.

Collapse
 
yoni333 profile image
yehonatan yehezkel

unfetch used only by 50k
"superagent" lib used by 250k and it much more maintained