2
votes

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.

2
I've checked it, but I still don't know how to modify into my ajax. I am new in developing javascript and rails.Coda Chang

2 Answers

5
votes

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.

1
votes

This is worked for me,

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