How to use axios versus fetch API

Axios and fetch() make requests to the server to get or post data in an asynchronous manner. In this shot, we will compare axios and fetch() and see how they can be used to perform different tasks.

Syntax

How to send a request (POST) with axios

Console

How to send a request (POST) with fetch

Console

Explanation

  • fetch() uses the body property, whereas axios uses the data property to send data.

  • The data in fetch() needs to be stringified, whereas the data in axios is a simple JavaScript object.

  • The URL is passed as an argument to fetch(), whereas the URL is set in the options object for axios.

  • The response object in fetch is also made into a string and needs an additional step to convert it into JSON format. However, in axios, the response object is already in the JSON format.

Response timeout

How to set response timeout with axios

Console

How to set response timeout with fetch

Console

Explanation

  • Axios provides the timeout property that is used in the config object to set the number of milliseconds before the request is aborted.

  • Fetch uses an AbortController object that allows us to abort the request using the signal property (read-only) of AbortController.

Backward compatibility

The USP of axios is its wide browser support. Old browsers like IE11 can also run axios without any issue. Fetch only supports Chrome 42+, Firefox 39+, Edge 14+, and Safari 10.1+.

Multiple requests

To make multiple requests, axios provides the axios.all() method. We can use axios.spread() to assign the properties of the response array to different variables.

axios.all([
  axios(options), 
  axios(options)
])
.then(axios.spread((obj1, obj2) => {
  console.log(obj1);
  console.log(obj2);
})

To make multiple requests, fetch provides the Promise.all() method.

Promise.all([
  fetch(URL, options), 
  fetch(URL, options)
])
.then([obj1, obj2] => {
  console.log(obj1);
  console.log(obj2);
})

Installation and usage

Axios is a third-party HTTP client for the browser that allows you to send asynchronous HTTP requests. First, we need to install axios in our application with npm or CDN. Fetch is a built-in, ready-to-use API that doesn’t require additional installations.

Free Resources