LoginSignup
13
4

More than 1 year has passed since last update.

【Rails7】Ajaxリクエスト時にCSRF tokenを含める(おそらく)公式のやり方

Last updated at Posted at 2022-05-19

巷にはX-CSRF-Tokenを手動で取得して送信するサンプルコードが溢れていますが、
一応公式で楽する方法が用意されています。

Rails6以前

rails-ujsに含まれるRails.ajaxメソッドを使うことで、自動でCSRF tokenをサーバーに送信できます。

const data = new FormData();
data.append("some_key", "some value");

Rails.ajax({
  url: "/some_resources",
  type: "POST",
  data: data,
  success: function(response) {
  }
});

Rails7以降

TurboフレームワークとStimulusが標準構成になり、rails-ujsは含まれなくなりました。
その代わり、上記ajax機能のみを切り出したrequest.jsというライブラリが公式で提供されています。
(本体に含まれているわけではないので事前にimportmapでpinする必要あり)

import { Controller } from '@hotwired/stimulus'
import { post } from '@rails/request.js'

export default class extends Controller {
  async hoge() {
    const response = await post("/some_resources", {
      body: { some_key: "some value" }
    })
    if(response.ok){
      ...
    }
  }
}


get, post, patch, put, destroy(deleteじゃないのか)などに対応したメソッドも用意されていて、
かつFormData以外に普通のObjectも渡せるようになっており便利。

詳細はこちらのREADMEに。

13
4
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
13
4