-12 C
New York
Saturday, February 4, 2023

Why JavaScript Developers Should Prefer Axios Over Fetch | by Sabesan Sathananthan


COMPARISON

Backward-compatibility, monitoring upload progress, and more

A dog catching a ball
Photo by Brixiv from Pexels

In my previous article, “Deep Insights Into JavaScript’s Fetch API”, I discussed the basics of the Fetch API. But it’s worth acknowledging that fetch() isn’t consistently an ideal solution, and there are sometimes better alternatives for making HTTP requests. Here I’ll describe why Axios is better than fetch() in development. This is my 36th Medium article.

Fetch

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 above piece of code is a simple fetch() get request. In the fetch() method, there’s one mandatory argument, which is url. url is a path from which the user would like to get data. Then fetch() method returns a promise that can resolve the response object or reject it with an error.

The second arguments in the fetch() method are options, and they’re optional. If the user won’t pass the options, the request always gets, and it downloads the content from the given URL. As I mentioned before, the promise returns the response object, and because of that, users need to use another method to get a body of the response. There are a few different methods that users can use depending on the format of the body.

  • response.json()
  • response.text()
  • response.blob()
  • response.formData()
  • response.arrayBuffer()

The most popular one is response.json().

Unfortunately, the built-in fetch() function is not in Node.js, but there is a polyfill like node-fetch. Between node-fetch and the browser fetch(), there exist several known variations.

Axios

Axios is a JavaScript library for making HTTP requests from Node or XMLHttpRequest or a browser. As a modern library, it’s based on the Promise API. Axios has some advantages, like protection against cross-site request forgery (CSFR) attacks. To be able to use the Axios library, users have to install it and import it to your project, using CDN, npm, Yarn, or Bower.

The above piece of code is a get method and a simple callback for a response and an error. When users are creating a config object, they can define a bunch of properties. The most common are url, baseURL, params, auth, headers, responseType, and data.

As a response, Axios returns a promise that’ll resolve with the response object or an error object. In the response object, there are the following values:

  • data: Actual response body
  • status: HTTP status code of the call, like 200 or 404
  • statusText: HTTP status as a text message
  • headers: The same as in the request
  • config: Request configuration
  • request: XMLHttpRequest (XHR) object

Users need to work with two promises in fetch(). Users can avoid boilerplate and write cleaner, more succinct code in Axios.

Axios uses the data property, but fetch() uses the body property to deal with data. fetch()’s data is stringified. In fetch(), the URL is passed as an argument, but in Axios the URL is set in the config object.

Fetch

Using the fetch() method, users need to use some kind of method on the response data. When users are sending the body with the request, users need to stringify the data.

In the above piece of code, with the response, users need to process the response.json() action. When dealing with the JSON data in fetch(), there is a two-step process. Users need to make the actual request first and then call the .json() method on the response.

Axios

In Axios users pass data in the request or get data from the response, and data is automatically stringified. Therefore, no other operations are required.

In the above example, you can see you just need one then.

Automatic transformation of data is a nice feature to have in Axios.

Fetch

Every time you get a response from the fetch() method, you need to check if the status is a success because even if it’s not, you’ll get the response. In the 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(). You could extract this error checking into a function to make it easier and more reusable.

Axios

In Axios, handling errors is pretty easy because Axios throws network errors. If there will be a bad response like 404, the promise will be rejected and will return an error. Therefore, you need to catch an error, and you can check what kind of error it was.

When loading large assets, progress indicators are very useful for users with slow internet speed. In previously implemented progress indicators. developers used XMLHttpRequest.onprogress as a callback handler.

Fetch

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

The above example demonstrates the use of ReadableStream to provide users with instant feedback while downloading images.

Axios

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

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.

Interception can be important for you when you need to check or change your HTTP request from the application to the server or the other way around — e.g., authentication, logging, etc.

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 it’ll take more code and can be more complicated than using Axios’s functionalities. You can overwrite the global fetch() method and define your own interceptor, like the following code:

Axios

Axios HTTP interception is one of the key features of this library — that’s why you don’t have to create additional code to use it.

In the above code, the axios.interceptors.request.use() and axios.interceptors.response.use() methods are used to define the code to be run before an HTTP request is sent.

Fetch

Fetch() provides the response timeout functionality through the AbortController interface.

In the above code, using the AbortController.AbortController() constructor, you need to create an AbortController object. The AbortController object allows you to later abort the request. As I mentioned in my previous article, “Deep Insights Into JavaScript’s Fetch API,” we discussed how signal is a property of AbortController, which is read-only. signal provides a way to communicate with a request or abort the request. If the server doesn’t respond in less than five seconds, the operation is terminated by calling controller.abort().

Axios

By using the optional timeout property in the config object, you can set the number of milliseconds before the request is terminated.

One of the reasons that JavaScript developers choose Axios rather than fetch() is the ease of setting timeout.

Fetch

To make multiple simultaneous requests, you could use the built-in Promise.all() method. Simply pass an array of fetch() requests to Promise.all() and then an async function to handle the response.

Axios

You can achieve the above result by using the axios.all() method provided by Axios. Pass all fetch requests as an array to the axios.all() method. Assign the properties of the response array to separate variables by using the axios.spread() function, like this:

Backward-compatibility is also known as browser support.

Fetch

Fetch() only supports Chrome 42+, Safari 10.1+, Firefox 39+, and Edge 14+. The full compatible table is available at “Can I Use?” In order to implement features similar to fetch() on web browsers that don’t support Fetch(), you can use fetch() with a polyfill like windows.fetch ().

To use the fetch polyfill, install it via this npm command:

npm install whatwg-fetch --save

If you need to access the polyfill implementation for some reason, it’s available via exports:

Bear in mind that you might also need a promise polyfill in some old browsers.

Axios

Axios isn’t like fetch(). Axios provides wide browser support. Even older browsers like IE11 can run Axios without an issue. The full compatibility table is available via Axios’s documentation.

For most of your HTTP communication needs, Axios provides an easy-to-use API in a compact package.

There are some alternative libraries for HTTP communication, such as ky, a tiny and elegant HTTP client based on window.fetch; superagent, a small, progressive client-side HTTP request library based on XMLHttpRequest.

But Axios is a better solution for applications with a lot of HTTP requests and for those that 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.

Related Articles

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Latest Articles