DEV Community

Rahul Kumar
Rahul Kumar

Posted on

Fetch vs. Axios HTTP Requests In JavaScript

Fetch:

Fetch is a newer way to send HTTP requests. Before Fetch, 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 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:

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);
 })
});
Enter fullscreen mode Exit fullscreen mode

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.

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:


<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

Using unpkg CDN:

<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
Enter fullscreen mode Exit fullscreen mode

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:

axios.get(‘URL’).then((response) => {   
   console.log(response.data)
   for (let student of data.results) {  
     console.log(student.name)
    }
 }).catch((error) => {
    console.log(error)
})
Enter fullscreen mode Exit fullscreen mode

Much cleaner and less code than with Fetch. Two key difference between Fetch and Axios are:

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.
We don’t have to parse JSON to retrieve data like Fetch.

Top comments (0)