12
15

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

Rails+AxiosでCSRF対策用のトークンを使う設定

Posted at

Rails+WebpackerのJavaScriptでAxiosを使うときは、POSTやPATCHで送信する際にCSRF対策用のトークンを指定する必要があります。送信のたびに指定するのは面倒なので、あらかじめ設定しておきましょう。

AxiosのInterceptorsの機能を使います。送信前にHTTPメソッドがPOST, PUT, PATCH, DELETEだったら、meta要素からトークンを取り出してHTTPヘッダにセットします。ここではjQueryを使っています。

サンプル: https://github.com/kazubon/blog-rails6-vuejs

app/javascript/axios_config.js
import Axios from 'axios';

Axios.interceptors.request.use((config) => {
  if(['post', 'put', 'patch', 'delete'].includes(config.method)) {
    config.headers['X-CSRF-Token'] = $('meta[name="csrf-token"]').attr('content');
  }
  return config;
}, (error) => {
  return Promise.reject(error);
});

このJavaScritptをどこかで動かします。とりあえずapplication.jsに入れとけばいいでしょう。

app/javascript/packs/application.js
import '../axios_config';

あとは、ふつうにAxiosが使えます。

import Axios from 'axios';

Axios.post('/entries.json', { entry: this.entry });
12
15
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
12
15

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?