"Axios" vs "Fetch" !depth

lausuarez02

Lautaro Suarez

Posted on May 2, 2023

"Axios" vs "Fetch" !depth

Post

I will start this post saying that this is just a simple and easy example of how to use it, but there is a lot more options and functionalities for each one.

What are they for?

Axios and fetch are widely used to make http requests in javascript and javascript frameworks.

Axios

Axios is a javascript library used to make http requests from nodeJS or XMLHttpRequests from browsers, with the support of the Promise API which is native to JS ES6.
Since it is a library we will have to install before using it.
Here we can see some of the things it is able to do:

  • Make XMLHttpRequests from the browser

  • Make HTTP requests from nodeJS

  • Support Promise API

  • Intercept request and response

  • Transform request and response data

  • Cancel Requests

  • Automatic transforms for JSON data

  • Client-side support for protecting agains XSRF

Fetch API

The Fetch API privides an interface for fetching resources.
It provides a generic definition of objects for requests and response. It also uses Promises and provides a global fetch() method.
This method only ask for one mandatory argument. It return a promise that resolves the response for this request, whether successful or not.
We will have to transform the data received into a json which is something that in axios will not be needed.

Security

We could say that Axios is less vulnerable since it has client-side protection against XSRF (Cross site Request Forgery).

Syntax

Axios and Fetch have a really similar syntax in general with just a couple of differences. Let`s see an example

Image description

Error Handling

When using Axios handling errors gets much easier since bad responses are automatically rejected, unlike Fetch, which even 404 or 500 errors, for example are still resolved. If let's say the backend return a "500 internal Server Error" code, Fetch will handle in the same way that it handles the code "200 Ok". To deal with this in Fetch, we can use the "ok" flag:

Image description

Axios error handling can be seen below:

Image description

Conclusion

I usually use axios when doing big projects so i have less code in my project and have a cleaner project.
Although lately i have been using fetch custom hook in my project to experiment a little bit more with it.
I encourage you to try both of them and make your own decision.

I hope someone found this post useFul and if you want to understand more about it you can read their respective documentation.

Lautaro.

💖 💪 🙅 🚩
lausuarez02
Lautaro Suarez

Posted on May 2, 2023

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related