Problem
I was trying to integrate a Rails API with a React front end when I encountered an error message:
Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at https://immense-savannah-47088.herokuapp.com/api/v1/books. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing
.
Solution
In an effort to solve the problem I tried several suggested solutions including this one I saw in a Medium article that requires the use of the rack-cors
ruby gem.
1. Add rack-cors Gem
In your gemfile you should add the following line or in some cases, it is commented out, you just need to uncomment it:
gem 'rack-cors', :require => 'rack/cors'
2. Bundle install
After adding the rack-cors
gem you will need to run the following command, to install the gem:
$ bundle install
3. Add the configuration in the Application.rb
Add the following lines of code to your application.rb
file:
module YourApp
class Application < Rails::Application
# ...
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
end
end
This should work as long as you won’t be using Heroku or other services that use Rack-based servers but if you intend to use Heroku then you will do this instead of the number three-step above.
4. Add the configuration in the Config.ru
Add the following lines of code to the end of your config.ru
file:
# ....
require 'rack/cors'
use Rack::Cors do
# allow all origins in development
allow do
origins '*'
resource '*',
:headers => :any,
:methods => [:get, :post, :delete, :put, :options]
end
end
Check the Ruby documentation for more information on using Rack middleware
and the MDN to learn more about CORS
.
Top comments (3)
If you are using Rails 6:
First go to your
Gemfile
and uncommentgem 'rack-cors'
. Then runbundle install
After that go to
config/initializers
folder. There, you should find a file calledcors.rb
.Uncomment the code that looks like this
change the line that says
origins 'example.com'
toorigin '*'
or if you're request will be originating from a particular origin, then set it accordingly.This worked for me. Hope it works for you as well. Cheers
@phillipug What if you don't have the cors.rb file on that folder? Create the file and paste the content you show above?
yes