WARNING: Can't verify CSRF token authenticity rails

后端 未结 17 1214
生来不讨喜
生来不讨喜 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条回答
  •  萌比男神i
    2020-11-22 06:22

    oops..

    I missed the following line in my application.js

    //= require jquery_ujs
    

    I replaced it and its working..

    ======= UPDATED =========

    After 5 years, I am back with Same error, now I have brand new Rails 5.1.6, and I found this post again. Just like circle of life.

    Now what was the issue is: Rails 5.1 removed support for jquery and jquery_ujs by default, and added

    //= require rails-ujs in application.js
    

    It does the following things:

    1. force confirmation dialogs for various actions;
    2. make non-GET requests from hyperlinks;
    3. make forms or hyperlinks submit data asynchronously with Ajax;
    4. have submit buttons become automatically disabled on form submit to prevent double-clicking. (from: https://github.com/rails/rails-ujs/tree/master)

    But why is it not including the csrf token for ajax request? If anyone know about this in detail just comment me. I appreciate that.

    Anyway I added the following in my custom js file to make it work (Thanks for other answers to help me reach this code):

    $( document ).ready(function() {
      $.ajaxSetup({
        headers: {
          'X-CSRF-Token': Rails.csrfToken()
        }
      });
      ----
      ----
    });
    

提交回复
热议问题