Skip to content Skip to sidebar Skip to footer

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

Solution 1:

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: (newDate()).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.

Solution 2:

This is worked for me,

$.ajax({
  beforeSend(xhr) {
    xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))
  },

Post a Comment for "Rails Post Can't Verify Csrf Token Authenticity"