top of page
Search

What is recommended for HTTP Requests/API calls: Fetch or Axios ultimate comparison

Writer's picture: sundeepdayalansundeepdayalan

Overview

Fetch — The Fetch API provides a JavaScript interface for accessing and manipulating parts of the HTTP pipeline, such as requests and responses. It also provides a global fetch() method that provides an easy, logical way to fetch resources asynchronously across the network.

Fetch() is part of a JavaScript window-object method within the Fetch API. It is built-in, so users don’t have to install it. Fetch() allows us to get data from the API asynchronously without installing any additional libraries.

The fetch() method takes one mandatory argument—the path to the resource you want to fetch—and returns a Promise that resolves with an object of the built-in Response class as soon as the server responds with headers. Let’s take a look at the syntax of the .fetch() method.



The second argument in .fetch() method are options, and it’s optional. If we won’t pass the options the request is always GET, and it downloads the content from the given URL. Inside the options parameter, we can pass methods or headers, so if we would like to use the POST method or any other, we have to use this optional array.



Once a Response is retrieved, the returned object contains the following properties:

  • response.body: A simple getter exposing a ReadableStream of the body contents

  • response.bodyUsed: Stores a Boolean that declares whether the body has been used in response yet

  • response.headers: The headers object associated with the response

  • response.ok: A Boolean indicating whether the response was successful or not

  • response.redirected: Indicates whether or not the response is the result of a redirect

  • response.status: The status code of the response

  • response.statusText: The status message corresponding to the status code

  • response.type: The type of the response

  • response.url: The URL of the response

There are a few different methods that we can use, depends on the format of the body that we need: response.json(), response.text(), response.formData(), response.blob(), response.arrayBuffer().

Let’s take a look at the code example with an optional parameter.



In the code example above, you can see the simple POST request with method, header, and body params.

Axios — Axios is a Javascript library used to make HTTP requests from node.js or XMLHttpRequests from the browser, and it supports the Promise API that is native to JS ES6.

Some core features of Axios, according to the documentation, are:

  • It can be used to intercept HTTP requests and responses.

  • It automatically transforms request and response data.

  • It enables client-side protection against CSRF.

  • It has built-in support for download progress.

  • It has the ability to cancel requests.

To be able to use axios library, we have to install it and import it to our project. axios can be installed using CDN, npm, or bower. Now let’s take a look at the syntax of a simple GET method.



In the code above, you can see how axios is used to create a simple GET request using .get() method. If you’d like to use the POST method in the function, then it’s enough to use .post() method instead and pass the request data as a parameter.

Axios also provides more functions to make other network requests as well, matching the HTTP verbs that you wish to execute, such as:

  • axios.request(config)

  • axios.get(url[, config])

  • axios.delete(url[, config])

  • axios.head(url[, config])

  • axios.options(url[, config])

  • axios.post(url[, data[, config]])

  • axios.put(url[, data[, config]])

  • axios.patch(url[, data[, config]])

When we are creating a config object we can define a bunch of properties, the most common are: baseUrl, params, headers, auth, responseType

As a response, axios returns a promise that will resolve with the response object or an error object. The response from a request contains the following information:

  • response.data: The response provided by the server

  • response.status: The HTTP status code from the server response, like 200 or 404

  • response.statusText: HTTP status message from the server response, for example, ok

  • response.headers: The headers that the server responded with

  • response.config: The config that was provided to axios for the request

  • response.request: The request that generated this response

Let’s take a look at the code example with the POST method with data.



In the code above, you can see the post method, where we put the config object as a param, with URL, data, and additional options.

We can also define the config object as a variable and pass it to the axios like in the example below.



Here, you can see that all the parameters, including URL, data, or method, are in the config object, so it may be easier to define everything in one place.

JSON data

Fetch — There is a two-step process when handling JSON data with fetch(). First, we have to make the actual request, and then we call the .json() method on the response i.e we need to use some kind of method on the response data, and when we are sending the body with the request, we need to stringify the data.

Axios — In axios it’s done automatically, so we just pass data in the request or get data from the response. It’s automatically stringified, so no other operations are required.

Let’s see how we can get data from fetch() and from axios.



In the example above, you can see that with axios we don’t have an additional line of code, where we have to convert data to JSON format, and we have this line in .fetch() example. In the case of a bigger project where you create a lot of calls, it’s more comfortable to use axios to avoid repeating the code.

Error handling

Axios — At this point, we also need to give points for axios as handling errors is pretty easy. If there will be a bad response like 404, the promise will be rejected and will return an error, so we need to catch an error, and we can check what kind of error it was, that’s it. Let’s see the code example.



In the code above, we’ve returned data when the response was good, but if the request failed in any way, we were able to check the type of error in .catch() part and return the proper message.

Fetch — With the .fetch() method, it’s a little bit more complicated. Every time we get a response from the .fetch() method, we need to check if the status is a success because even if it’s not, we will get the response. In case of .fetch() , a promise won’t be resolved if and only if the request won’t be completed. Fetch() doesn’t throw network errors. Therefore, you must always check the response.ok property when you work with fetch(). Let’s see the code example.



In this code, we’ve checked the status of the code in the promise object, and if the response had status ok, then we could process and use .json() method, but if not, we had to return an error inside .then().

For easy and proper error handling, axios will be definitely a better solution for your project, but still, if you are building a small project with one or two requests, it’s fine to use .fetch(), but you need to remember to handle errors correctly.

HTTP interception

HTTP interception can be important when we need to check or change our HTTP requests from the application to the server, or in the other way, for example, for authentication, logging.

Axios — In the case of axios HTTP interception is one of the key features of this library, that’s why we don’t have to create additional code to use it. Let’s take a look at the code example to see how easy we can do it.



In the code, you can see the request interception and response interception. In the first case, we created a console.log informing about sending requests, and in the response interception, we can do any action on response and then return it.

Fetch — .fetch() doesn’t provide the HTTP interception by default, there’s a possibility to overwrite the .fetch() method and define what needs to happen during sending the request, but of course, it will take more code and can be more complicated than using axios functionality.

Response timeout

Axios — In Axios, you can use the optional timeout property in the config object to set the number of milliseconds before the request is aborted. For example:



Fetch — Fetch() provides similar functionality through the AbortController interface. It’s not as simple as the Axios version, though:



Here, we create an AbortController object using the AbortController.AbortController() constructor, which allows us to later abort the request. signal is a read-only property of AbortController providing a means to communicate with a request or abort it. If the server doesn’t respond in less than four seconds, controller.abort() is called, and the operation is terminated.

The simplicity of setting timeout in Axios is one of the reasons some developers prefer it to fetch().

Simultaneous requests

Axios — To make multiple simultaneous requests, Axios provides the axios.all() method. Simply pass an array of requests to this method, then use axios.spread() to assign the properties of the response array to separate variables:



Fetch — We can achieve the same result by using the built-in Promise.all() method. Pass all fetch requests as an array to Promise.all(). Next, handle the response by using an async function, like this:



Download progress

When we have to download a large amount of data, a way to follow the progress would be useful, especially when users have slow internet. Earlier, to implement progress indicators developers used XMLHttpRequest.onprogress callback. In .fetch() and axios, there are different ways to do it.

Fetch — To track the progress of the download in .fetch() we can use one of the response.body properties, a ReadableStream object. It provides body data chunk by chunk, and it allows us to count how much data is consumed in time.

Axios — In axios, implementing a progress indicator is possible as well, and it’s even easier because there exists a ready module, which can be installed and implemented; it’s called Axios Progress Bar.

If you have a lot of large data to download and you want to track the progress in progress indicator, you can manage that easier and faster with axios but .fetch() gives the possibility as well, just it needs more code to be developed for the same result.

Upload progress

Fetch — In fetch(), you can’t monitor the progress of your uploads.

Axios — In Axios, you can monitor the progress of your uploads. This could be a deal-breaker if you’re developing an application for video or photo uploading.



Browser support (Backward Compatibility)

Axios — Axios has wide browser support. Compatibility table

Fetch — Fetch only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+. If you need to support older browsers, a polyfill is available. Compatibility table

Conclusion

In this guide, we have looked at Fetch and Axios and checked out some real-world operations. This comparison shows that Axios is a better solution in the case of an application where there are a lot of HTTP requests which need good error handling or HTTP interceptions. In the case of small projects, with just a few simple API calls, Fetch can be a good solution as well.

With this knowledge, I hope you are able to select the best solution for you, and you find this comparison helpful.



Thanks for reading. Consider sharing!

14 views0 comments

Recent Posts

See All

Comments


b1b60f666d5345775184d3a0d1ec7225.png

Contact us via

Subscribe to Our Newsletter

Thanks for submitting!

Follow Us On:

  • Twitter
  • Instagram

© 2021 by Crado

bottom of page