Gorakh Nath
Gorakh Nath

Reputation: 9858

What is difference between Axios and Fetch?

I'm trying to call a web service for my application, and there are two options available: Fetch and Axios. I'm not sure which one to choose, so I'm looking for information to help me decide. Can you explain the differences between the two and their advantages? I'd appreciate it if you could keep your explanation simple and easy to understand.

Upvotes: 348

Views: 212735

Answers (12)

Daniel
Daniel

Reputation: 15413

Axios is a stand-alone third 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 it's 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.

Upvotes: 12

c-chavez
c-chavez

Reputation: 7496

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.

Upvotes: 331

Artem S. Zhelonkin
Artem S. Zhelonkin

Reputation: 210

fetch

fetch is a native API available in modern browsers. "Native" in the context of browser APIs means that the feature is built into the browser's JavaScript environment without the need for external scripts or plugins. It's a standard part of the environment. For instance, fetch is now a standard part of the Web Platform API, which modern browsers aim to support. It's like how XMLHttpRequest (which gave rise to AJAX) is native to browsers, even if it wasn't always the case. For fetch, while it's native to modern browsers, it's true that older browsers like IE require a polyfill (a script that provides the functionality of a newer feature in older browsers that don't natively support it).

Pros:

  • Native: Doesn't require any additional packages or libraries to use.
  • Promise-based: Easily use with async/await.
  • Readable syntax: Especially for simple GET requests.

Cons:

  • Error Handling: Doesn't reject on HTTP error statuses (e.g., 404 or 500) but only on network errors or request failures.
  • Features: Some advanced features (like request timeout, request cancellation) are not natively supported or require additional work.
  • JSON Parsing: Requires an additional step to parse JSON (response.json()).

axios

axios is a popular third-party HTTP client library.

Pros:

  • Error Handling: Rejects the promise on HTTP error statuses, which can simplify error handling.
  • Interceptors: Provides the ability to intercept requests and responses before they are handled or sent.
  • Timeouts: Built-in support for request timeouts.
  • Cancellable Requests: Supports request cancellation using the CancelToken feature.
  • Automatic JSON Parsing: Automatically parses JSON data from responses.
  • Wider Browser Support: Has built-in XHR handling which provides compatibility with older browsers.
  • Transforms: Allows data to be transformed before it's sent or after it's received.

Cons:

  • External Dependency: Adds an additional dependency to your project.
  • Size: While not massive, it's still larger than the native fetch.

Upvotes: 4

Bhupatsinh
Bhupatsinh

Reputation: 38

Axios is an HTTP client library based on promises whereas Fetch is a javascript API for making API requests.

  1. The Main difference is browser support: Axios supports all browsers including IE whereas Fetch is supported by the latest browser only and IE does not support it.

Reference link:https://github.com/axios/axios#browser-support

https://caniuse.com/fetch

  1. Axios has better error handling compare to fetch API. Axios can throw 400 to 500 range status code errors whereas in fetch API you need to manually handle the errors. For more: https://bariablogger.in/f/axios-vs-fetch-react

Upvotes: 2

Thilina Sampath
Thilina Sampath

Reputation: 3775

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.

Upvotes: 45

cdsaenz
cdsaenz

Reputation: 550

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);
  }

Upvotes: 0

ANIL PATEL
ANIL PATEL

Reputation: 743

  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

Upvotes: 15

Amin Gholami
Amin Gholami

Reputation: 25

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

Upvotes: 0

Lucas Katayama
Lucas Katayama

Reputation: 4570

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

Upvotes: 85

Vaibhav KB
Vaibhav KB

Reputation: 1745

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)

Upvotes: 23

Jairo Malanay
Jairo Malanay

Reputation: 1347

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

Upvotes: 12

cyberwombat
cyberwombat

Reputation: 40104

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.

Upvotes: 5

Related Questions