Use fetch!

Which is better? axios or fetch? Let me share my (unconventional, as always: ) opinion.



There are few articles comparing fetch vs axios, and saying that axios is better… but when you read them, the pros are not so compelling in my opinion. The main point is that axios has better error handling, and that it returns JSON with no extra effort. On the other hand, the fact that fetch is already there, and you can use it natively is a huge win. I found that fetch is more generic and I trust that the smart people that is building the web did the right thing.

The good new is that

Few lines of code are needed to implement axios features, using fetch.

Show me the code

Suppose you want to launch an API request, on some url, authenticated by a JWT token.

// It is supposed that variables `url` and `token` are given.
fetch(`${url}`, {
  method: 'GET',
  headers: {
    'Accept': 'application/json',
    'Authorization': `BEARER ${token}`,
    'Content-Type': 'application/json'
}).then(res => res.ok ? res.json() : new Error(res.statusText))
  .then(data => { console.log(data) })
  .catch(err => { throw err })

Note that this function checks response status and returns it as JSON.

res => res.ok ? res.json() : new Error(res.statusText)