WARNING: Can't verify CSRF token authenticity rails
I am sending data from view to controller with AJAXand I got this error:
WARNING: Can't verify CSRF token authenticity
I think I have to send this token with data.
Does anyone know how can I do this ?
Edit: My solution
I did this by putting the following code inside the AJAX post:
headers: {
'X-Transaction': 'POST Example',
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
},
You should do this:
Make sure that you have <%= csrf_meta_tag %>
in your layout
Add beforeSend
to all the ajax request to set the header like below:
$.ajax({ url: 'YOUR URL HERE',
type: 'POST',
beforeSend: function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))},
data: 'someData=' + someData,
success: function(response) {
$('#someDiv').html(response);
}
});
To send token in all requests you can use:
$.ajaxSetup({
headers: {
'X-CSRF-Token': $('meta[name="csrf-token"]').attr('content')
}
});
The best way to do this is actually just use <%= form_authenticity_token.to_s %>
to print out the token directly in your rails code. You dont need to use javascript to search the dom for the csrf token as other posts mention. just add the headers option as below;
$.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) %>"
})
If I remember correctly, you have to add the following code to your form, to get rid of this problem:
<%= token_tag(nil) %>
Don't forget the parameter.
链接地址: http://www.djcxy.com/p/63556.html上一篇: 在控制台中禁用Rails SQL日志记录
下一篇: 警告:无法验证CSRF令牌真实性轨道