Fetch vs. Axios HTTP Requests In JavaScript
Tags: javascript
Published: 2021-03-01 03:02:44

## Fetch:
Fetch is a newer way to send HTTP requests. Before Fetch, [XMLHttpRequest](https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest) was a very popular way to send requests. In fact, it was the only way to send HTTP requests in the early days of JavaScript. XMLHttpRequest does not support [promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) and mostly relies on callbacks if we have nested requests, which could be too repetitive and hard to read. That’s when Fetch entered. 

Fetch supports `promises`. It is way cleaner and readable than XMLHttpRequest requests, at least in my experience. Here is an example of fetch request:
```javascript
fetch('URL')   //instead of URL use which ever URL you want to send a request
.then((response) => {
    if (!response.ok)
       throw new Error(`Status Code Error: ${response.status}`)
    response.json()	//parse json
.then((data) => {
    for (let student of data.results) {	  //assuming data is list of students and has property name
        console.log(student.name)
    }
})
.catch((err) => {
    console.log('SOMETHING WENT WRONG WITH FETCH!');
    console.log(err);
 })
});
```

Here, the first `.then` gives us a response object, it resolves but we can not access the data yet. The data we need is inside the `body` key with the value `ReadableStream`. To access the data we use `response.json()` as shown above which parses JSON and we get the data we need. Now the second `.then` gives us the data and we are looping through it to display the student’s name. This is the scenario of when the  `promise` resolves, but what happens when something goes wrong with the URL and the `promise` gets rejected? In that case, we handle it with `.catch` like above. You might be thinking what is that if statement for? Well, adding `.catch` doesn’t catch the error if something goes wrong with `fetch`. It will give us a 404 status response instead of catching the error because the response.json() line fails if the response gets rejected, so we are trying to parse something that doesn’t exist. So by adding the if statement, we are checking if we have the response, and only then parse JSON. To read more about Fetch you can refer to this [documentation](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API#concepts_and_usage).

## Axios:
Axios is a library for making HTTP Requests. It’s one of the most popular libraries that simplifies the process of making HTTP Requests. Unlike `fetch` it’s not a built-in option. It’s an external library that uses `fetch` behind the scenes. It is promise-based like `fetch` which means we don’t have to deal with a lot of callbacks. One nice feature Axios has is, it can be used on the server-side as well with `node.js`. 

To use Axios, you can add a script tag on the Html file like so: 

Using jsDelivr CDN:
```html
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
```
Using unpkg CDN:
```html
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
```
Or you can download it with the following commands:

Using npm:

> $ npm install axios

Using bower:

> $ bower install axios

Using yarn:

> $ yarn add axios

Now let’s make the same `GET Request` from the above example with Axios:
```javascript
axios.get(‘URL’).then((response) => {	
   console.log(response.data)
   for (let student of data.results) {	
     console.log(student.name)
    }
 }).catch((error) => {
    console.log(error)
})
```
Much cleaner and less code than with Fetch. Two key difference between Fetch and Axios are:
1. We don’t have to manually check the response of the status code as we did in a fetch request. Axios knows to display the catch error if the status code is not `200 - ok`.
2. We don’t have to parse JSON to retrieve data like Fetch.