WARNING: Can't verify CSRF token authenticity rails

后端 未结 17 1007
生来不讨喜
生来不讨喜 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:26

    Use jquery.csrf (https://github.com/swordray/jquery.csrf).

    • Rails 5.1 or later

      $ yarn add jquery.csrf
      
      //= require jquery.csrf
      
    • Rails 5.0 or before

      source 'https://rails-assets.org' do
        gem 'rails-assets-jquery.csrf'
      end
      
      //= require jquery.csrf
      
    • Source code

      (function($) {
        $(document).ajaxSend(function(e, xhr, options) {
          var token = $('meta[name="csrf-token"]').attr('content');
          if (token) xhr.setRequestHeader('X-CSRF-Token', token);
        });
      })(jQuery);
      

提交回复
热议问题