我用AJAXand发送数据从视图到控制器,我得到了这个错误:

警告:无法验证CSRF令牌的真实性

我想我必须用数据发送这个令牌。

有人知道我该怎么做吗?

编辑:我的解决方案

我通过在AJAX帖子中放入以下代码来做到这一点:

headers: {
  'X-Transaction': 'POST Example',
  'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},

当前回答

确保在布局中有<%= csrf_meta_tag %> 添加beforeSend在ajax请求中包含csrf-令牌,以设置头部。这只需要post请求。

读取csrf-token的代码在rails/jquery-ujs中可用,所以以我之见,使用它是最简单的,如下所示:

$.ajax({
  url: url,
  method: 'post',
  beforeSend: $.rails.CSRFProtection,
  data: {
    // ...
  }
})

其他回答

如果你没有使用jQuery,而是使用类似于获取API的请求,你可以使用下面的方法来获取csrf-token:

文档。querySelector(“元[name =“csrf-token”]”)。getAttribute(“内容”)

fetch('/users', {
  method: 'POST',
  headers: {
    'Accept': 'application/json',
    'Content-Type': 'application/json',
    'X-CSRF-Token': document.querySelector('meta[name="csrf-token"]').getAttribute('content')},
    credentials: 'same-origin',
    body: JSON.stringify( { id: 1, name: 'some user' } )
    })
    .then(function(data) {
      console.log('request succeeded with JSON response', data)
    }).catch(function(error) {
      console.log('request failed', error)
    })

使用jquery。csrf (https://github.com/swordray/jquery.csrf)。

Rails 5.1或更高版本 添加jquery.csrf //= require jquery.csrf Rails 5.0或之前版本 来源“https://rails-assets.org”做 宝石的rails-assets-jquery.csrf 结束 //= require jquery.csrf 源代码 (函数(美元){ 美元(文档)。ajaxSend(函数(e, xhr,选项){ var牌= $(“元[name = " csrf-token]”).attr(“内容”); If (token) xhr。setRequestHeader(“X-CSRF-Token”,令牌); }); }) (jQuery);

确保在布局中有<%= csrf_meta_tag %> 添加beforeSend在ajax请求中包含csrf-令牌,以设置头部。这只需要post请求。

读取csrf-token的代码在rails/jquery-ujs中可用,所以以我之见,使用它是最简单的,如下所示:

$.ajax({
  url: url,
  method: 'post',
  beforeSend: $.rails.CSRFProtection,
  data: {
    // ...
  }
})

如果我没记错的话,你必须添加以下代码到你的表单,以摆脱这个问题:

<%= token_tag(nil) %>

不要忘记参数。

最好的方法实际上是使用<%= form_authenticity_token。To_s %>直接在rails代码中打印令牌。你不需要像其他文章提到的那样使用javascript来搜索dom中的csrf令牌。只需添加标题选项如下;

$.ajax({
  type: 'post',
  data: $(this).sortable('serialize'),
  headers: {
    'X-CSRF-Token': '<%= form_authenticity_token.to_s %>'
  },
  complete: function(request){},
  url: "<%= sort_widget_images_path(@widget) %>"
})