导轨阿贾克斯无法验证CSRF令牌真实性 [英] Rails Ajax Can't verify CSRF token Authenticity

查看:134
本文介绍了导轨阿贾克斯无法验证CSRF令牌真实性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的Rails应用我收到警告:无法验证CSRF令牌的真实性的一个ajax岗位的API。

应用/视图/布局/ application.html.haml

 !
%HTML
  %头
    = stylesheet_link_tag应用程序,:媒体=> 所有
    = javascript_include_tag应用程序
    = csrf_meta_tags
  %体
    =产量
 

阿贾克斯后

  $阿贾克斯(网址:{url:#{card_credits_path}',
 键入:POST,
 beforeSend:功能(XHR){xhr.setRequestHeader(X-CSRF令牌,#{form_authenticity_token}')},
 数据类型:JSON,
 数据:{credit_uri:response.data.uri,
         电子邮件:$('#电子邮件:隐藏)VAL()。
         名称:$('名')VAL()。
       },
成功:函数(randomobject){
   了window.location ='/';
   },
错误:函数(){
   的console.log(卡的信息是错误的!);
   }
});
 

解决方案

假设你已经设置令牌使用Rails的 csrf_meta_tag 标记的CSRF,请求的令牌将可在 CSRF令牌 meta标签:

 < META CONTENT =uniquetokenNAME =CSRF令牌/>
 

由于您使用jQuery,您可以令牌通过调用下面的值的 beforeSend 键传递到您的AJAX请求:

 函数(XHR){xhr.setRequestHeader(X-CSRF令牌',$('元[NAME =CSRF令牌])。ATTR(内容 ))}
 

In my rails app I'm getting "WARNING: Can't verify CSRF token authenticity" on an ajax post to an api.

app/views/layouts/application.html.haml :

!!!
%html
  %head
    = stylesheet_link_tag "application", :media => "all"
    = javascript_include_tag "application"
    = csrf_meta_tags
  %body
    = yield

ajax post :

$.ajax({ url: '#{card_credits_path}',
 type: 'POST',
 beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', '#{form_authenticity_token}')},
 dataType: "json",
 data: { credit_uri: response.data.uri,
         email: $('#email:hidden').val(),
         name: $('.name').val()
       },
success: function(randomobject) {
   window.location = '/';
   },
error: function(){
   console.log("Card information is wrong!");
   }
});

解决方案

Assuming you've set the CSRF token using the Rails csrf_meta_tag tag, the request's token will be available in the csrf-token meta tag:

<meta content="u-n-i-q-u-e-t-o-k-e-n" name="csrf-token" />

Since you're using jQuery, you can pass the token to your AJAX request by invoking the following value for the beforeSend key:

function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}

这篇关于导轨阿贾克斯无法验证CSRF令牌真实性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆