Use fetch!

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

Web

Motivation

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(response => {
  if (response.ok) {
    response.json()
  } else {
    return Promise.reject({
      status: response.status,
      statusText: response.statusText
    })
  }
}).then(data => { console.log(data) })
  .catch(err => { throw err })

If you want to see a complete example of a tiny fetch wrapper, checkout this TypeScript implementation.