rails6 API post時にエラー「ActionController::InvalidAuthenticityToken」が発生

rails6 API post時にエラー「ActionController::InvalidAuthenticityToken」が発生

rails6で、APIでpost時にエラー「ActionController::InvalidAuthenticityToken」が発生した場合の対処法を記述してます。railsのバージョンは6.1.0です。

環境

  • OS ubuntu20.10
  • ruby 2.7.2
  • rails 6.1.0
  • Postgresql 13.1 (dockerで構築)

エラー全文

APIでpost実行時に発生。
※クラス名は「CustomersController」

ActionController::InvalidAuthenticityToken

原因

CSRF対策(Cross-Site Request Forgery)のトークンがないために発生。

対処法

コード内に「protect_from_forgery」を追加するか、

class Api::CustomersController < ApplicationController
  protect_from_forgery

トークンを無視します。

class Api::CustomersController < ApplicationController
  skip_before_action :verify_authenticity_token

以下を実行して、postできることが確認できました。

curl -X POST localhost:3000/api/customers -d 'customer[name]=hoge&cust
omer[email]=test@test.com'