【Ruby on Rails】「No 'Access-Control-Allow-Origin' header is present on the requested resource」を回避する.
なにがあったか
クライアント(Angular5)から、API(Rails5)にHTTPリクエストをしようとしたところ、次のようなエラーが出た。
No 'Access-Control-Allow-Origin' header is present on the requested resource.
原因
Same-Origin Policyに引っかかっていました。
今回、API側とクライアン側はそれぞれ次のように実行しており、
- API側:
http://localhost:3000
- CLIENT側
http://localhost:4200
portが3000
と4200
なので、この2つは異なるオリジン、いわゆるクロスオリジンの関係です。それにも関わらずに、HTTPリクエストを行おうとしていたためSame-Origin Policyに引っかかり上記のようなエラーが表示されていました。
解決策
- Gemfileに
gem rack-cors
を追記または、コメントアウトを外してbundle installする。
- config/initializers/cors.rbのコメントアウトを外す。
- originsは利用するものに書き換える。
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
origins 'http://localhost:3000', 'https://residenti-blog.herokuapp.com/'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
gem rack-cors
を追記または、コメントアウトを外してbundle installする。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
origins 'http://localhost:3000', 'https://residenti-blog.herokuapp.com/'
resource '*',
headers: :any,
methods: [:get, :post, :put, :patch, :delete, :options, :head]
end
end
そして最後に、サーバーを再起動します。
Author And Source
この問題について(【Ruby on Rails】「No 'Access-Control-Allow-Origin' header is present on the requested resource」を回避する.), 我々は、より多くの情報をここで見つけました https://qiita.com/residenti/items/3a03e5e0268b354284b7著者帰属:元の著者の情報は、元のURLに含まれています。著作権は原作者に属する。
Content is automatically searched and collected through network algorithms . If there is a violation . Please contact us . We will adjust (correct author information ,or delete content ) as soon as possible .