Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any reasons to use axios instead ES6 fetch [closed]

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?

like image 269
Sasha Kos Avatar asked May 10 '18 16:05

Sasha Kos


People also ask

Why should we use Axios instead of fetch?

Without question, some developers prefer Axios over built-in APIs for its ease of use. But many overestimate the need for such a library. The fetch() API is perfectly capable of reproducing the key features of Axios, and it has the added advantage of being readily available in all modern browsers.

Should I learn fetch or Axios?

Axios is best suited in terms of the transformation of data as it transforms data of JSON automatically whereas fetch requires two steps for the transformation of JSON data. If you want to transform JSON data using the Fetch API, then first you have to make a request then in response, a JSON function is called.

What are disadvantages of fetch API?

XHR limitations and drawbacks:more complicated API, request and response concepts are mixed together. lacks streaming, whole response is going to buffer in memory, not available for binary data.

What is the purpose of Axios?

Axios is a promised-based HTTP client for JavaScript. It has the ability to make HTTP requests from the browser and handle the transformation of request and response data.


2 Answers

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     }), }) 
  1. 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.

like image 64
mpontus Avatar answered Sep 21 '22 02:09

mpontus


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.

like image 43
Karen Grigoryan Avatar answered Sep 20 '22 02:09

Karen Grigoryan