Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the differences in using Axios vs jQuery for HTTP requests?

I've been a jQuery user since forever. But now I'm building my first API that uses JWT for authentication. This said, most tutorials I find online to consume this API with authentication headers use Axios to make these requests.

I am already using jQuery on the project, so, I would love to make simple jQuery ajax calls, but I'm not sure if there's any hard drawbacks to using it.

This would be my jQuery code:

$.ajax({   url: "http://localhost:8080/login",   type: 'POST',   data: formData,   error : function(err) {     console.log('Error!', err)   },   success: function(data) {     console.log('Success!')     localStorage.setItem('token', data.id_token);   } }); 

Send the Request

$.ajax({   url: "http://localhost:8080/login",   type: 'GET',   // Fetch the stored token from localStorage and set in the header   headers: {"Authorization": localStorage.getItem('token')} }); 

After reading the Axios features, the last one is: Client side support for protecting against XSRF . Does jQuery ajax not support that? Would I have to do anything extra to make this protection? Is there anything else that makes it worth using another library like Axios instead of jQuery?

like image 755
sigmaxf Avatar asked Jul 21 '17 21:07

sigmaxf


People also ask

Which is better Ajax or Axios?

Ajax is a standard and web development technique (Ajax (programming) - Wikipedia ). Axios is just a JavaScript library that helps you to use Ajax easier. There are other JavaScript libraries, such as jQuery (jQuery ), Request (request/request ), Fetch (github/fetch ), that help to do similar functionalities.

What is the benefit of using Axios?

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.

Can I use Axios in jQuery?

Yes, you can use axios with any library and it does not conflict when used with jquery as it's not dependent on any other library.

Why we use Axios instead of fetch?

Key Differences: With Axios, the data is sent through the data property of the options, but Fetch API uses the body property. Fetch response requires additional validation as it always returns a response object no matter whether it is successful or not. The data in fetch() has been serialized to a String (Stringified).


2 Answers

I do not see any explicit support for that in the jQuery $.ajax documentation. That being said, it is something you could do with the beforeSend setting. In the beforeSend you would modify the jqHXR to include your XSRF information.

@charlietfl mentioned you can also do this in global ajaxSend() so it is applied to all instances of $.ajax()

This is what axios is doing:

  // `xsrfCookieName` is the name of the cookie to use as a value for xsrf token   xsrfCookieName: 'XSRF-TOKEN', // default    // `xsrfHeaderName` is the name of the http header that carries the xsrf token value   xsrfHeaderName: 'X-XSRF-TOKEN', // default 

If you are already using jQuery in your project, and you can handle the XSRF yourself, then use $.ajax().

"Is there anything else that makes it worth using another library like Axios instead of jQuery?"

I would say most definitely. A library dedicated to handling http decouples the process from your application framework or presentation library.

like image 199
Kyle Richardson Avatar answered Sep 26 '22 16:09

Kyle Richardson


Adding support for CSRF (XSRF) in jquery is as simple as adding the following lines to your page after jquery has loaded (with your token rendered in a meta tag on your page):

$.ajaxSetup({     headers: {         'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')     } }); 

I have found (in the past) that Axios is more trouble than it's worth. Simple procedures, like performing A GET request to request a resource listing, altering an item in the listing with a POST/PUT/DELETE request, and then re-requesting the listing (to synchronise the view) causes cached data to be served, meaning the view does not change. This is just one example.

Edit: I'm curently working on a Vue.js project, and I remembered a few more reasons why I stuck with jquery over axios:

It's worth noting that if you use bootstrap or something similar, you already have jquery included, so why include a second library?

And finally, I use a simple script which converts any standard html form to an ajax submission form simply by adding a couple of classes, and a bootstrap-alert to display errors. It's intended for use with laravel, and (optionally) Vue.js. It's really handy because it handles styling of the form components to tell the user what is happening. For debugging server side errors you can just remove the "ajax-submit" class from the form and it will revert to standard form submission. The anciliary operations in the script are most simply implemented using jQuery. I have put it in a gist here. Hopefully someone will find it useful.

I would actually be very interested to see how difficult it is to create an equivalent script using Axios, and excluding jQuery

Further Edit: I just had to remove Axios from yet another project. It is a PWA app and Axios does not have an option to use the fetch API which is required for use with service workers. I created a gist to replace Axios with fetch here. Maybe it will be of some use to someone.

like image 29
mp035 Avatar answered Sep 22 '22 16:09

mp035