RailsでCORSエラーを解消する

プログラミング

勉強でバックエンドRails, フロントVue3のアプリを作成時に

VueからRailsのAPIにリクエスト時にCORSエラー

Access to XMLHttpRequest at 'http://localhost:3000/api/v1/users' from origin 'http://localhost:5173' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

これを解決した際のメモ

Railsは7.1.3を使用

解消手順

Railsにはrack-corsというgemが用意されているのでこれを利用

Gemfileでrack-corsがコメントアウトされている場合は解除、ない場合は追記

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

インストールします

bundle install

次にrack-corsの設定ファイル(config/initializers/cors.rb)を修正

アクセスを許可したいドメイン(今回はlocalhost:5173想定)

とヘッダー、メソッドを設定

全部のメソッドを許可したい場合は下記でOK

# 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
    origins "http://localhost:5173"

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

あとはRailsを再起動すればOK

これで解消しました

ちなみにVue側のリクエスト設定は下記記事に書いてあるので興味ある方は読んでみてください

タイトルとURLをコピーしました