Before you go, check out these stories!

0
Hackernoon logoAxios or Fetch: What Is Better for HTTP Requests? by@thatIITGirl

Axios or Fetch: What Is Better for HTTP Requests?

Author profile picture

@thatIITGirlthatIITGirl

Node js developer

Ever wondered why developers are going for Axios over fetch? As we are aware both are the means to deal with HTTP or XMLHttp requests, Both are capable of making all types of API calls (get, post,put.. etc.). Both are based on Promise API which is native to ES6. But what are the major points to be noted?

First, .fetch() has a two-steps process while handling JSON data. The first makes the actual request and then the second is to call theย .json() method on the response.

const url = 'https://api.spotify.com/v1/artists/0OdUWJ0sBjDrqHygGUXeCF'

fetch(url)
.then(response => response.json())
.then(data => console.log(data));

As a good developer, our main aim is to minimize the code. Axios deals it with a single line.

const url = 'https://api.spotify.com/v1/artists/0OdUWJ0sBjDrqHygGUXeCF'

axios.get(url)
.then(response => console.log(response));

with Axios, we get the result in JSON format by default.

Second is, Error handling. Logically ifย .fetch() gets an error it would enter theย .catch() block and should return but, it eventually executes the next then() in chain. see below:

But Axios handles it, the way it is expected.

it returns from catch, no more .then() chaining.

So, .fetch() method is a great way of getting HTTP requests native in ES6, but there are just few gotchas, that could be dealt by these third party libraries.ย 

Tags

The Noonification banner

Subscribe to get your daily round-up of top tech stories!