I've check this WARNING: Can't verify CSRF token authenticity rails but I still can't figure it out why it cause this error.
Here is my ajax
$.post(
"<%= ajax_chats_path %>",
{timestamp :(new Date()).getTime(),msg: $('#msg').val()},
function (json) {
console.log(json);
});
If I add this
skip_before_action :verify_authenticity_token
in controller, it can solve this problem.
I am not sure it's the right way to do, because it looks like it may encounter some security attack.
I've check this WARNING: Can't verify CSRF token authenticity rails but I still can't figure it out why it cause this error.
Here is my ajax
$.post(
"<%= ajax_chats_path %>",
{timestamp :(new Date()).getTime(),msg: $('#msg').val()},
function (json) {
console.log(json);
});
If I add this
skip_before_action :verify_authenticity_token
in controller, it can solve this problem.
I am not sure it's the right way to do, because it looks like it may encounter some security attack.
Share Improve this question edited May 23, 2017 at 12:08 CommunityBot 11 silver badge asked May 20, 2016 at 3:56 rj487rj487 4,6347 gold badges49 silver badges94 bronze badges 2- please see here. stackoverflow./questions/7203304/… – Shani Commented May 20, 2016 at 4:26
- I've checked it, but I still don't know how to modify into my ajax. I am new in developing javascript and rails. – rj487 Commented May 20, 2016 at 4:50
2 Answers
Reset to default 6You're missing the CSRF token in your Ajax call. You'll need to use a long-form $.ajax call, and add this:
beforeSend: $.rails.CSRFProtection
Instead of $.post
, you can use the $.ajax
equivalent, which would look like this:
$.ajax({
type: "POST",
url: "<%= ajax_chats_path %>",
beforeSend: $.rails.CSRFProtection,
data: {
timestamp: (new Date()).getTime(),
msg: $('#msg').val(),
beforeSend: $.rails.CSRFProtection
},
success: function (json) {
console.log(json);
}
});
You should also strongly consider adding the datatype
field to the call, so that jQuery knows the disposition of the response and can handle it accordingly. You can choose from any of "xml", "json", "html", "script", "jsonp", or "text". See the jQuery.ajax() API documentation for more details.
This is worked for me,
$.ajax({
beforeSend(xhr) {
xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
},