📖
ローカル開発時RailsとNext.jsでポート番号を変えているときのクロスエラー
Access to XMLHttpRequest at 'http://localhost:3001/api/v1/posts/' 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.
xhr.js:251 POST http://localhost:3001/api/v1/posts/ net::ERR_FAILED
今回は3000側のクライアント側からの3001の方(Rails側)にアクセスしようとしたらブロックされてしまったよとのこと。
Railsのgemfileの
# Use Rack CORS for handling Cross-Origin Resource Sharing (CORS), making cross-origin AJAX possible
# gem "rack-cors"
ここをコメントアウト外して
bundle install
/config/intializer/cors.rbの
以下の部分をコマンとアウトを外して
# Rails.application.config.middleware.insert_before 0, Rack::Cors do
# allow do
# origins "example.com"
#
# resource "*",
# headers: :any,
# methods: [:get, :post, :put, :patch, :delete, :options, :head]
# end
# end
origins "example.com"
↓
origins "localhost:3000"
これで解消する
Discussion