【发布时间】:2023-03-26 12:10:02
【问题描述】:
在我的 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!");
}
});
【问题讨论】:
-
你验证
form_authenticity_token的内容了吗?内容是什么? -
不,我没有,我不确定该怎么做。让我看看我能做什么。
-
不需要...您可以从相应的元标记中提取令牌值。我已经发布了一个解决方案来演示如何做到这一点。
标签: jquery ruby-on-rails ruby ajax