Open1

CORS 設定 for Rails

sutoneasutonea

フロントに Vue、バックに Rails を利用した際、CORSに関するエラーが発生した。
対応としては、Rails に以下の設定をすればOK

Gemfile

# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin Ajax possible
gem "rack-cors"

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 # http://localhost:5173 は vue が起動するポート
    origins "http://localhost:3000", "http://localhost:5173"

    resource "*",
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end