Allow anything through CORS Policy
Solution 1:
I've your same requirements on a public API for which I used rails-api.
I've also set header in a before filter. It looks like this:
headers['Access-Control-Allow-Origin'] = '*'
headers['Access-Control-Allow-Methods'] = 'POST, PUT, DELETE, GET, OPTIONS'
headers['Access-Control-Request-Method'] = '*'
headers['Access-Control-Allow-Headers'] = 'Origin, X-Requested-With, Content-Type, Accept, Authorization'
It seems you missed the Access-Control-Request-Method header.
Solution 2:
Have a look at the rack-cors middleware. It will handle CORS headers in a configurable manner.
Solution 3:
Simply you can add rack-cors gem https://rubygems.org/gems/rack-cors/versions/0.4.0
1st Step: add gem to your Gemfile:
gem 'rack-cors', :require => 'rack/cors'
and then save and run bundle install
2nd Step: update your config/application.rb file by adding this:
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
for more details you can go to https://github.com/cyu/rack-cors Specailly if you don't use rails 5.
Solution 4:
I had issues, especially with Chrome as well. What you did looks essentially like what I did in my application. The only difference is that I am responding with a correct hostnames in my Origin CORS headers and not a wildcard. It seems to me that Chrome is picky with this.
Switching between development and production is a pain, so I wrote this little function which helps me in development mode and also in production mode. All of the following things happen in my application_controller.rb
unless otherwise noted, it might not be the best solution, but rack-cors didn't work for me either, I can't remember why.
def add_cors_headers
origin = request.headers["Origin"]
unless (not origin.nil?) and (origin == "http://localhost" or origin.starts_with? "http://localhost:")
origin = "https://your.production-site.org"
end
headers['Access-Control-Allow-Origin'] = origin
headers['Access-Control-Allow-Methods'] = 'POST, GET, OPTIONS, PUT, DELETE'
allow_headers = request.headers["Access-Control-Request-Headers"]
if allow_headers.nil?
#shouldn't happen, but better be safe
allow_headers = 'Origin, Authorization, Accept, Content-Type'
end
headers['Access-Control-Allow-Headers'] = allow_headers
headers['Access-Control-Allow-Credentials'] = 'true'
headers['Access-Control-Max-Age'] = '1728000'
end
And then I have this little thing in my application_controller.rb
because my site requires a login:
before_filter :add_cors_headers
before_filter {authenticate_user! unless request.method == "OPTIONS"}
In my routes.rb
I also have this thing:
match '*path', :controller => 'application', :action => 'empty', :constraints => {:method => "OPTIONS"}
and this method looks like this:
def empty
render :nothing => true
end