2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

[Rails] CSRF tokenでエラー対応方法

Last updated at Posted at 2021-04-13

[Rails]CSRF tokenでエラー対応方法

CSRF tokenでエラー

Can't verify CSRF token authenticity.

エラー対応方法

①CSRF tokenをHTMLソースコードに追加する。

<!DOCTYPE html>
<html>
  <head>
    <title> タイトル </title>
    <%= csrf_meta_tags %>  <<==これを追加する
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_pack_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

②ajaxPrefilterにcsrf-tokenを格納する。

$.ajaxPrefilter(function(options, originalOptions, jqXHR) {
    var token;
    if (!options.crossDomain) {
    token = $('meta[name="csrf-token"]').attr('content');
       if (token) {
          return jqXHR.setRequestHeader('X-CSRF-Token', token);
        }
     }
 });

③headersにcsrf-tokenを格納する。

$(function() {

    $.ajax({
      type: 'PATCH',
      url: '/comments/' + commentId,
      data: {
        comment: {
          body: body
        },
      },
      headers: {
          'X-CSRF-Token' : $('meta[name="csrf-token"]').attr('content')
      },
      dataType: 'json',
    }).done(function (data) {

    }).fail(function () {

    });
  })
});
2
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?