title | published | description | tags | cover_image |
---|---|---|---|---|
Setting Up CORS On A Rails App |
true |
Setting up CORS on a Rails API to allow communications with a front end app. |
Rails, CORS, API, React |
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
.
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.
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'
After adding the rack-cors
gem you will need to run the following command, to install the gem:
$ bundle install
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.
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
.