【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が30004200なので、この2つは異なるオリジン、いわゆるクロスオリジンの関係です。それにも関わらずに、HTTPリクエストを行おうとしていたためSame-Origin Policyに引っかかり上記のようなエラーが表示されていました。

解決策

  1. Gemfileにgem rack-corsを追記または、コメントアウトを外してbundle installする。
  2. config/initializers/cors.rbのコメントアウトを外す。
  3. 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

そして最後に、サーバーを再起動します。