rack-cors
をインストール
Gemfileに以下を追記してbundle install
します。
Gemfile
gem 'rack-cors'
bundle install
configを作成
config/initializers/cors.rb
に設定を記述します。
config/initializers/cors.rb
# Be sure to restart your server when you modify this file.
# Avoid CORS issues when API is called from the frontend app.
# Handle Cross-Origin Resource Sharing (CORS) in order to accept cross-origin AJAX requests.
# Read more: https://github.com/cyu/rack-cors
Rails.application.config.middleware.insert_before 0, Rack::Cors do
allow do
# 許可するオリジンを記述(APIを叩く側のドメインを記述)。
origins 'localhost:3000'
# 許可するリソースファイルを記述
resource '*',
headers: :any, # CORS リソース要求で許可される HTTP ヘッダー
expose: ["access-token", "expiry", "token-type", "uid", "client"], # レスポンスの HTTP ヘッダをクライアントに公開
methods: [:get, :post, :put, :patch, :delete, :options, :head], # 許可するメソッドを記述
end
end