15
9

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 5 years have passed since last update.

Railsのajax送信の際にCSRF tokenでエラー

Last updated at Posted at 2019-05-02

CSRF tokenでエラー解消方法メモ

  • エラー内容
    • Can't verify CSRF token authenticity.

1つ目:コントローラで制御

controller
  # CSRF保護を無効
  protect_from_forgery :except => [:create] #対象のアクションに修正

でも可能。

2つ目:Ajaxで送信する前にtokenを取得し送信する

jsファイル
$.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);
        }
     }
 });
  1. $.ajaxPrefilter( [dataTypes], handler )
    ajax送信する事前に処理を行う
    ajaxリファレンス
  2. token取得
    token = $('meta[name="csrf-token"]').attr('content');
  3. tokenをリクエストヘッダに入れる
    jqXHR.setRequestHeader('X-CSRF-Token', token)
15
9
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
15
9

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?