在我的rails应用程序中,我在向api的ajax发布中收到“警告:无法验证CSRF令牌的真实性”。
app / views / layouts / application.html.haml :
!!! %html %head = stylesheet_link_tag "application", :media => "all" = javascript_include_tag "application" = csrf_meta_tags %body = yield
ajax发布 :
$.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!"); } });
假设您已使用Rails csrf_meta_tag标记设置了CSRF令牌,则请求的令牌将在csrf-tokenmeta标记中可用:
csrf_meta_tag
csrf-token
<meta content="u-n-i-q-u-e-t-o-k-e-n" name="csrf-token" />
由于使用的是jQuery,因此可以通过为beforeSend密钥调用以下值来将令牌传递给AJAX请求:
beforeSend
function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}