Is there any reasons to use axios instead ES6 fetch

JavascriptEcmascript 6Axios

Javascript Problem Overview


Studied the documentation of axios and of ES6 fetch I found than both are quite similar and have experienced a strong influence of $.ajax and its shorthands.

Main advantage of axios is browser support.

So am I right that if I use babel-polyfill - there is no reasons to use axios?

Javascript Solutions


Solution 1 - Javascript

A few reasons for using Axios over Fetch:

  1. Ability to monitor request progress

This is more of a question between XMLHttpRequest (which powers axios) or Fetch API.

Fetch API currently does not provide any way to get notified of the request progress, a feature which powers feedback mechanism for large file uploads for example.

Axios, on the other hand, has this functionality built in:

axios.post('/api', data, {
    onUploadProgress: ({ total, loaded }) => {
        // update progress
    }),
})

2. Error handling

When your backend returns 500 Internal Server Error response code, fetch will not treat it any different from 200 OK.

This is an inconvenience in most cases since all your previous assumptions of what a response would look like are no longer valid.

Most often, when receiving an erroneous response from the server you'd want to abort the processing pipeline as soon as possible, and switch to an error handling case.

fetch(url)
    .then(reponse => {
        if (!(status >= 200 && status < 300)) {
            return Promise.reject(new Error("Invalid response status"));
        }
        
        return response;
    })
    .then(response => response.json())
    .then(/* normal processing */)
    .catch(/* error handling */);
    

This is not hard to accomplish, but you'd probably want to capture this logic under some abstraction to avoid repetition, and this brings us one step closer to Web API abstraction which is Axios.

Axios does a sane thing and rejects the promise if the response returns erroneous status. This behavior is customizable as are most of the things with axios.

  1. Testing

Axios has moxios, fetch has fetch-mock.

Both of those libraries are great but in my experience, fetch-mock required additional setup to get Jest to use mocked fetch over polyfilled one.

I also like that moxios.wait() returns a promise which will be resolved after matching the request.

  1. Other features that Axios offers

For example, you can configure an interceptor which will add api key to all request parameters, or monitor active requests to show a loading screen.


Reasons for using one option over the other may vary from actual requirements to convenience.

If you need to monitor progress, use Axios (or XMLHttpRequest).

If you are writing a service worker, use Fetch.

Otherwise, use what's more convenient to you.

Solution 2 - Javascript

This:

fetch('https://jsonplaceholder.typicode.com/posts', {
    method: 'POST',
    body: JSON.stringify({
      title,
      body
    })
  }).then((res) => {
    if (res.ok) {
      return res.json()
    }

    throw new Error(res.responseText);

  })
  .then((data) => console.log(data))
  .catch((err) => console.log(err))

can essentially be expressed by axios with this:

axios.post('https://jsonplaceholder.typicode.com/posts', {
    title,
    body
  }).then((data) => console.log(data))
  .catch((err) => console.log(err))

So in essence:

  1. No need to do res.json(), res.text() etc
  2. No need to handle res.ok in order to catch non 200 status errors in actual promise catch handler.
  3. No need to stringify payload, it's handled by axios by default.

Overall axios provides a more higher level and simple api to work with requests.

Solution 3 - Javascript

Axios is an NPM library and therefore works on both Node.js and the browser. fetch is a Web API and is not available to Node. Conversely, Node.js has the http module and does not have the Fetch API. It also simplifies passing data and handling different types of HTTP Requests

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionSasha KosView Question on Stackoverflow
Solution 1 - JavascriptmpontusView Answer on Stackoverflow
Solution 2 - JavascriptKaren GrigoryanView Answer on Stackoverflow
Solution 3 - JavascriptMeghanView Answer on Stackoverflow