LoginSignup
1
0

crosエラーの解決方法

Last updated at Posted at 2023-05-21

CORSは何かというと、「どこからのリクエストを許可するのか」ということです。

・この記事を書く経緯
RailsとReactでアプリ開発をしていたときに、このようなエラーに遭遇したので忘れないように記事にしました。

Access to XMLHttpRequest at 'http://localhost:3065/user' from origin 
'http://localhost:3000' has been blocked by CORS policy: Response to
 preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' 
header is present on the requested resource.

・解決策
結論として解決策は以下の通りになります。

  1. Gemfileに以下のgemを追加します。
gem 'rack-cors'

2.bundle installを実行します。
3. config/initializers/cors.rbを作成し、以下のように記述します。

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins 'localhost:3000' #ReactのサーバーのURLを設定してください。
    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :delete, :options, :head],
      credentials: true
  end
end

4.Railsのconfig/application.rbに以下を追加します。

config.middleware.use ActionDispatch::Cookies
config.middleware.use ActionDispatch::Session::CookieStore

これでCORSの設定が完了し、ReactのフロントエンドからRailsのAPIを呼び出すことができるようになります。
ただし、この設定により、すべてのリクエストに対してCORSが有効になるため、セキュリティーには十分に注意してください。必要に応じて、originsmethodsなどを適宜変更してください。

1
0
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
1
0