When do you need axios?
Tags: webdev, javascript, beginners, react
Published: 2019-08-31 00:09:46

# 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](https://dev.to/fleepgeek/react-throwaway-app-2-movie-search-app-3f3d). 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](https://www.youtube.com/channel/UCXX74aetH0OPVYNxxcVpTJw) 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](https://dev.to/fleepgeek/react-throwaway-app-2-movie-search-app-3f3d) 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.

```javascript
// 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:

```javascript
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:

```javascript
// 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:

```javascript
// 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](https://github.com/axios/axios#interceptors).

Finally, `axios` provides a simple API that lets you cancel requests. 
Modern browsers have started implementing an [experimental feature](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#Aborting_a_fetch) 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](https://github.com/axios/axios) docs for more information.

I hope this article was helpful.
Thanks for reading.
All the best