What is difference between Axios and Fetch?

154,730

Solution 1

Fetch and Axios are very similar in functionality, but for more backwards compatibility Axios seems to work better (fetch doesn't work in IE 11 for example, check this post)

Also, if you work with JSON requests, the following are some differences I stumbled upon with.

Fetch JSON post request

let url = 'https://someurl.com';
let options = {
            method: 'POST',
            mode: 'cors',
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            body: JSON.stringify({
                property_one: value_one,
                property_two: value_two
            })
        };
let response = await fetch(url, options);
let responseOK = response && response.ok;
if (responseOK) {
    let data = await response.json();
    // do something with data
}

Axios JSON post request

let url = 'https://someurl.com';
let options = {
            method: 'POST',
            url: url,
            headers: {
                'Accept': 'application/json',
                'Content-Type': 'application/json;charset=UTF-8'
            },
            data: {
                property_one: value_one,
                property_two: value_two
            }
        };
let response = await axios(options);
let responseOK = response && response.status === 200 && response.statusText === 'OK';
if (responseOK) {
    let data = await response.data;
    // do something with data
}

So:

  • Fetch's body = Axios' data
  • Fetch's body has to be stringified, Axios' data contains the object
  • Fetch has no url in request object, Axios has url in request object
  • Fetch request function includes the url as parameter, Axios request function does not include the url as parameter.
  • Fetch request is ok when response object contains the ok property, Axios request is ok when status is 200 and statusText is 'OK'
  • To get the json object response: in fetch call the json() function on the response object, in Axios get data property of the response object.

Solution 2

They are HTTP request libraries...

I end up with the same doubt but the table in this post makes me go with isomorphic-fetch. Which is fetch but works with NodeJS.

http://andrewhfarmer.com/ajax-libraries/


The link above is dead The same table is here: https://www.javascriptstuff.com/ajax-libraries/

Or here: enter image description here

Solution 3

According to mzabriskie on GitHub:

Overall they are very similar. Some benefits of axios:

  • Transformers: allow performing transforms on data before a request is made or after a response is received

  • Interceptors: allow you to alter the request or response entirely (headers as well). also, perform async operations before a request is made or before Promise settles

  • Built-in XSRF protection

please check Browser Support Axios

browser support table

I think you should use axios.

Solution 4

One more major difference between fetch API & axios API

  • While using service worker, you have to use fetch API only if you want to intercept the HTTP request
  • Ex. While performing caching in PWA using service worker you won't be able to cache if you are using axios API (it works only with fetch API)

Solution 5

Axios is a stand-alone 3rd party package that can be easily installed into a React project using NPM.

The other option you mentioned is the fetch function. Unlike Axios, fetch() is built into most modern browsers. With fetch you do not need to install a third party package.

So its up to you, you can go with fetch() and potentially mess up if you don't know what you are doing OR just use Axios which is more straightforward in my opinion.

Share:
154,730

Related videos on Youtube

Gorakh Nath
Author by

Gorakh Nath

Leading team from more than 4 years and taking the ownership of features development using reactjs, redux,c# asp.net, mvc, nodejs, gatsby, contentful,graphql, jest,chai, mocha, contentful,scss.Good understanding of algorithm and data-structure.

Updated on March 15, 2022

Comments

  • Gorakh Nath
    Gorakh Nath about 2 years

    I am calling the web service by using Fetch but the same I can do with the help of Axios. So now I am confused. Should I go for either Axios or Fetch?

    • Jaydeep Solanki
      Jaydeep Solanki over 7 years
      I think this has been discussed in a great detail over github.com/mzabriskie/axios/issues/314
    • Qiulang
      Qiulang over 3 years
      Although there are many answers but I find nobody mentions the request timeout that axiso has over fetch.
  • Gorakh Nath
    Gorakh Nath over 7 years
    Still I am not able to find the benefit of fetch over axios. Can you have any idea why I should go with the axios?
  • Gorakh Nath
    Gorakh Nath over 7 years
    I have found some of the difference as:- Overall they are very similar. Some benefits of axios: Transformers: allow performing transforms on data before request is made or after response is received Interceptors: allow you to alter the request or response entirely (headers as well). also perform async operations before request is made or before Promise settles Built-in XSRF protection
  • Lucas Katayama
    Lucas Katayama over 7 years
    I think fetch is a standard see fetch.spec.whatwg.org ... axios could have more features because it doesn't follow that.... I think in the end they do the basics (ajax http request) but it depends on what you need... I didn't need a transformer ... so getting a standard lib is a pro...
  • Luca Fagioli
    Luca Fagioli about 7 years
    Be aware that that table is misleading. It defines fetch as Native (Meaning you can just use it - no need to include a library, accordingly to the table source), while actually fetch is not implemented in some platforms (notably in all versions of IE), for which you need to provide an external polyfill anyway.
  • Apurva jain
    Apurva jain over 6 years
    Adding to the difference mentioned by @jack123 fetch also doesn't provide a basic ajax functionality like timeout (which is very weird) we have to use a separate module to implement this basic functionality.
  • CoderPJ
    CoderPJ over 6 years
    @LucasKatayama fetch is not a library. It is a method present on the window object. It serves the same purpose an XMLhttpRequest object serves, but is more composable as is it Promise based. Now, Axios is a library. You need to import it into your application using CommonJS's require, or use import, if use are using a node application or using node modules.
  • John Anisere
    John Anisere over 6 years
    @APJ Is it safe to say "axios API" like people say "fetch API" ? and why is fetch called an API?
  • CoderPJ
    CoderPJ over 6 years
    @JohnAnisere axios is not an API. It is just another library. It is a promise based HTTP client. axios is not available on the window object of the browser. Go to your console and see it for yourself. Type "this.fetch". You'll be able to see the returned function. Now try doing "this.axios". You'll see 'undefined' because it is not directly available on the window. You need to install it using bower, npm or using the cdn in your application. It is safe to call fetch an API because it is directly attached to the window, like the ServiceWorker API.
  • Dave Newton
    Dave Newton almost 6 years
    @CoderPJ How an API is implemented isn't relevant, though; all libraries have an API. You can't randomly assume this.fetch will be meaningful, e.g., IE: caniuse.com/#feat=fetch.
  • CodeFinity
    CodeFinity almost 6 years
    Agreed. Axios is also small enuff import so that bloat is not much concern - as opposed to something like express or mongoose where if one is a bit insane about package size, they might be concerned. :)
  • cyberwombat
    cyberwombat over 5 years
    @baitun these are from me running unit tests which (I think I was using Mocha) often have a .throws method to test errors thrown. In this case I was testing rejections from al 3 libs and noticed the difference in the data that was returned.
  • vancy-pants
    vancy-pants almost 5 years
    @LucasKatayama The link appears to be broken
  • tamj0rd2
    tamj0rd2 over 4 years
    The link is dead. I wish the actual answer was in your response
  • Lucas Katayama
    Lucas Katayama over 4 years
    @tamj0rd2 just posted another link.
  • c-chavez
    c-chavez over 4 years
    isomorphic-fetch is very good, but not maintained as axios is. Latest commit for isomorphic was on may 2016... latest commit for axios, 15 hours ago. Axios has more contributors, more examples, basically better help. That's why I kept axios before isomorphic-fetch.
  • Tom Stickel
    Tom Stickel over 4 years
    Can anyone verify this is really true? It is 1 person, but the 9 upvotes seem to agree yet it would be nice to see comments on this ( I'm using axios with service worker pwa offline is why I ask.
  • Tom Stickel
    Tom Stickel over 4 years
    Fetch is ok, but Axios is like you said - more straightforward. That which is built into modern browsers (fetch) isn't that great for feature releases. - so I prefer Axios
  • Vaibhav KB
    Vaibhav KB over 4 years
    Sure, we can have few more comments on this but I was facing issues with caching while using axios and when I replaced axios with fetch() APIs it got resolved
  • Yang Wang
    Yang Wang almost 4 years
    Here is more question. Once responseOk is true, do we need to check the status in response.data if it has status provided? thanks
  • leonbloy
    leonbloy almost 4 years
    Axios request is ok when status is 200 and statusText is 'OK' What about other httpStatus in the 2xx range like 201 or 204?
  • arkhz
    arkhz almost 4 years
    This seems to be correct, but might be fixed in a near future: github.com/axios/axios/pull/2891
  • nonopolarity
    nonopolarity over 3 years
    or I think response.ok is a boolean, and the true or false value indicates whether response was ok. User offline is handled by the fetch() rejecting, but other types of server error is handled by response.ok