239

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?

Floern
  • 31,495
  • 23
  • 98
  • 115
Gorakh Nath
  • 6,352
  • 11
  • 33
  • 58

10 Answers10

213

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.

Hope this helps.

c-chavez
  • 5,673
  • 4
  • 28
  • 43
  • Here is more question. Once responseOk is true, do we need to check the status in response.data if it has status provided? thanks – Yang Wang May 24 '20 at 00:36
  • 5
    `Axios request is ok when status is 200 and statusText is 'OK'` What about other httpStatus in the 2xx range like 201 or 204? – leonbloy May 26 '20 at 17:37
  • 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` – nonopolarity Feb 11 '21 at 12:54
56

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

Lucas Katayama
  • 3,371
  • 22
  • 28
  • 7
    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 Nov 28 '16 at 12:50
  • 1
    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 – Gorakh Nath Nov 28 '16 at 12:51
  • 4
    I think fetch is a standard see https://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... – Lucas Katayama Nov 28 '16 at 12:59
  • 4
    Be aware that [that table](http://andrewhfarmer.com/ajax-libraries/) 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](http://caniuse.com/#feat=fetch) (notably in all versions of IE), for which you need to provide an external polyfill anyway. – Luca Fagioli Apr 20 '17 at 12:06
  • 3
    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. – Apurva jain Oct 02 '17 at 15:00
  • @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. – CoderPJ Dec 23 '17 at 22:03
  • @APJ Is it safe to say "axios API" like people say "fetch API" ? and why is fetch called an API? – John Anisere Jan 11 '18 at 14:31
  • @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. – CoderPJ Jan 12 '18 at 19:18
  • @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: https://caniuse.com/#feat=fetch. – Dave Newton Jun 27 '18 at 13:24
  • 2
    @LucasKatayama The link appears to be broken – vancy-pants Aug 08 '19 at 23:44
  • The link is dead. I wish the actual answer was in your response – tamj0rd2 Aug 21 '19 at 16:02
  • 1
    @tamj0rd2 just posted another link. – Lucas Katayama Aug 22 '19 at 00:12
  • 1
    [isomorphic-fetch](https://github.com/matthew-andrews/isomorphic-fetch) is very good, but not maintained as [axios](https://github.com/axios/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. – c-chavez Sep 06 '19 at 07:15
35

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

enter image description here

I think you should use axios.

Thilina Sampath
  • 2,860
  • 5
  • 32
  • 59
  • 4
    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. :) – CodeFinity Aug 13 '18 at 12:18
  • 1
    Please don't revert legitimate edits, or copy content without attribution. – jonrsharpe Oct 24 '18 at 16:08
11

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)
Vaibhav KB
  • 1,407
  • 15
  • 16
  • 7
    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 Dec 03 '19 at 23:11
  • 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 – Vaibhav KB Jan 13 '20 at 10:09
  • 1
    This seems to be correct, but might be fixed in a near future: https://github.com/axios/axios/pull/2891 – arkhz Jun 25 '20 at 07:08
10

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.

Daniel
  • 9,020
  • 8
  • 63
  • 101
  • 1
    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 – Tom Stickel Dec 03 '19 at 23:14
5

In addition... I was playing around with various libs in my test and noticed their different handling of 4xx requests. In this case my test returns a json object with a 400 response. This is how 3 popular libs handle the response:

// request-promise-native
const body = request({ url: url, json: true })
const res = await t.throws(body);
console.log(res.error)


// node-fetch
const body = await fetch(url)
console.log(await body.json())


// Axios
const body = axios.get(url)
const res = await t.throws(body);
console.log(res.response.data)

Of interest is that request-promise-native and axios throw on 4xx response while node-fetch doesn't. Also fetch uses a promise for json parsing.

cyberwombat
  • 31,246
  • 30
  • 143
  • 210
  • 1
    @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. – cyberwombat Nov 05 '18 at 00:02
5

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

Advantages of axios over fetch

Jairo Malanay
  • 1,189
  • 8
  • 12
3
  1. Fetch API, need to deal with two promises to get the response data in JSON Object property. While axios result into JSON object.

  2. Also error handling is different in fetch, as it does not handle server side error in the catch block, the Promise returned from fetch() won’t reject on HTTP error status even if the response is an HTTP 404 or 500. Instead, it will resolve normally (with ok status set to false), and it will only reject on network failure or if anything prevented the request from completing. While in axios you can catch all error in catch block.

I will say better to use axios, straightforward to handle interceptors, headers config, set cookies and error handling.

Refer this

ANIL PATEL
  • 389
  • 2
  • 10
0

With fetch, we need to deal with two promises. With axios, we can directly access the JSON result inside the response object data property.

0

A job I do a lot it seems, it's to send forms via ajax, that usually includes an attachment and several input fields. In the more classic workflow (HTML/PHP/JQuery) I've used $.ajax() in the client and PHP on the server with total success.

I've used axios for dart/flutter but now I'm learning react for building my web sites, and JQuery doesn't make sense.

Problem is axios is giving me some headaches with PHP on the other side, when posting both normal input fields and uploading a file in the same form. I tried $_POST and file_get_contents("php://input") in PHP, sending from axios with FormData or using a json construct, but I can never get both the file upload and the input fields.

On the other hand with Fetch I've been successful with this code:

var formid = e.target.id;

// populate FormData
var fd    = buildFormData(formid);       

// post to remote
fetch('apiurl.php', {
  method: 'POST',
  body: fd,
  headers: 
  {
     'Authorization' : 'auth',
     "X-Requested-With" : "XMLHttpRequest"
  }
})    

On the PHP side I'm able to retrieve the uploads via $_FILES and processing the other fields data via $_POST:

  $posts = [];
  foreach ($_POST as $post) {
      $posts[] =  json_decode($post);
  }
cdsaenz
  • 383
  • 6
  • 13