简体   繁体   中英

webpack jquery ajax rails 5 InvalidAuthenticityToken

I use Rails 5.1 + webpack When I include jQuery to my project with

 plugins: [
    new webpack.ProvidePlugin({
        'jQuery': 'jquery',
        '$': 'jquery',
        'global.jQuery': 'jquery'
    })
  ]

And try to use jQuery.ajax PUT, POST, or DELETE requests eg

var that = this;
$.ajax({
  url: navigator_item.url,
  method: 'DELETE',
  success: function(res) {
   ...
  }
});

I get ActionController::InvalidAuthenticityToken .

But, when I include jQuery with next line in app.js file

import $ from 'jquery'
window.jQuery = $;
window.$ = $; // lazy fix if you want to use jQuery in your inline scripts.

and this in shared.js

module.exports = {
  resolve: {
    alias: {
        'jquery': 'jquery/src/jquery'
    }
  }

jQuery.ajax works fine.

Is there a way using jQuery.ajax when you include jQuery as a plugin?

The ActionController::InvalidAuthenticityToken has nothing to do with jQuery.

You have to pass an authenticity_token parameter with all your PUT , POST and DELETE requests.

To do that you can usually fetch it from the header with $('[name="csrf-token"]')[0].content

So your request would look something like:

var that = this;
$.ajax({
  url: navigator_item.url,
  data: { authenticity_token: $('[name="csrf-token"]')[0].content},
  method: 'DELETE',
  success: function(res) {
   ...
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM