Coda Chang Coda Chang - 6 months ago 28
Ajax Question

Rails post can't verify CSRF token authenticity

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.

Answer

You'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.

Comments