Allow CORS in Ruby on Rails
I was able to figure this out with a bit of help from @Akiomi's answer:
In my routes.rb
, I added the following code to the top of the file:
match '(:anything)' => 'application#nothing', via: [:options]
Next, in my application controller, I added:
def nothing
render text: '', content_type: 'text/plain'
end
Along with the headers in config/application.rb
:
config.action_dispatch.default_headers = {
'Access-Control-Allow-Origin' => '*',
'Access-Control-Request-Method' => 'GET, PATCH, PUT, POST, OPTIONS, DELETE',
'Access-Control-Allow-Headers:' => 'Origin, X-Requested-With, Content-Type, Accept'
}
Yes, notice the 'Access-Control-Allow-Headers:' => 'Origin, X-Requested-With, Content-Type, Accept'
that was not included in my original question, this is one of the big problems.
I spent some time working on this and I can tell you the most reliable solution is to use rack-cors. see: https://github.com/cyu/rack-cors
First add the gem:
gem 'rack-cors', '~> 0.3.1'
then in application.rb
add
config.middleware.insert_before ActionDispatch::Static, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
If your production app does not serve static assets (such as if you use a serve like nginx or apache), consider replacing ActionDispatch::Static
in the above example with 0
. See https://github.com/cyu/rack-cors#common-gotchas for more information about the argument.