简体   繁体   English

webpack jquery ajax rails 5 InvalidAuthenticityToken

[英]webpack jquery ajax rails 5 InvalidAuthenticityToken

I use Rails 5.1 + webpack When I include jQuery to my project with 当我将jQuery包含到我的项目中时,我使用Rails 5.1 + webpack

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

And try to use jQuery.ajax PUT, POST, or DELETE requests eg 并尝试使用jQuery.ajax PUT,POST或DELETE请求,例如

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

I get ActionController::InvalidAuthenticityToken . 我得到了ActionController::InvalidAuthenticityToken

But, when I include jQuery with next line in app.js file 但是,当我在app.js文件的下一行包含jQuery时

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

and this in shared.js 这在shared.js中

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

jQuery.ajax works fine. jQuery.ajax正常工作。

Is there a way using jQuery.ajax when you include jQuery as a plugin? 当您将jQuery作为插件包含时,是否可以使用jQuery.ajax

The ActionController::InvalidAuthenticityToken has nothing to do with jQuery. ActionController::InvalidAuthenticityToken与jQuery无关。

You have to pass an authenticity_token parameter with all your PUT , POST and DELETE requests. 您必须通过所有PUTPOSTDELETE请求传递一个authenticity_token参数。

To do that you can usually fetch it from the header with $('[name="csrf-token"]')[0].content 为此,通常可以使用$('[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) {
   ...
  }
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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