Rails Ajax Can't verify CSRF token Authenticity

后端 未结 2 593
日久生厌
日久生厌 2020-12-30 07:09

In my rails app I\'m getting \"WARNING: Can\'t verify CSRF token authenticity\" on an ajax post to an api.

app/views/layouts/application.html.haml<

相关标签:
2条回答
  • 2020-12-30 07:47

    Assuming you've set the CSRF token using the Rails csrf_meta_tag tag, the request's token will be available in the csrf-token meta tag:

    <meta content="u-n-i-q-u-e-t-o-k-e-n" name="csrf-token" />
    

    Since you're using jQuery, you can pass the token to your AJAX request by invoking the following value for the beforeSend key:

    function(xhr) {xhr.setRequestHeader('X-CSRF-Token', $('meta[name="csrf-token"]').attr('content'))}
    
    0 讨论(0)
  • 2020-12-30 07:47

    This code is already present in the rails/jquery-ujs, so it is a lot easier to just use that:

     beforeSend: $.rails.CSRFProtection
    
    0 讨论(0)
提交回复
热议问题