WARNING: Can't verify CSRF token authenticity rails

后端 未结 17 1202
生来不讨喜
生来不讨喜 2020-11-22 06:05

I am sending data from view to controller with AJAXand I got this error:

WARNING: Can\'t verify CSRF token authenticity

I think

17条回答
  •  迷失自我
    2020-11-22 06:07

    1. Make sure that you have <%= csrf_meta_tag %> in your layout
    2. Add a beforeSend to include the csrf-token in the ajax request to set the header. This is only required for post requests.

    The code to read the csrf-token is available in the rails/jquery-ujs, so imho it is easiest to just use that, as follows:

    $.ajax({
      url: url,
      method: 'post',
      beforeSend: $.rails.CSRFProtection,
      data: {
        // ...
      }
    })
    

提交回复
热议问题