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
How to send a request (POST) with fetch
Explanation
-
fetch()uses thebodyproperty, whereasaxiosuses thedataproperty to send data. -
The data in
fetch()needs to bestringified, whereas the data inaxiosis a simple JavaScript object. -
The URL is passed as an argument to
fetch(), whereas the URL is set in the options object foraxios. -
The response object in
fetchis also made into a string and needs an additional step to convert it into JSON format. However, inaxios, the response object is already in the JSON format.
Response timeout
How to set response timeout with axios
How to set response timeout with fetch
Explanation
-
Axiosprovides thetimeoutproperty that is used in theconfigobject to set the number of milliseconds before the request is aborted. -
Fetchuses anAbortControllerobject that allows us to abort the request using thesignalproperty (read-only) ofAbortController.
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.