Rails route routing for CORS
I am implementing CORS on rails APIs and basically want to define a route that says "All API call requests via OPTIONS method should go to controller action. cors
"
The relative parts of what I have so far:
# routes.rb:
scope :module => 'api', :path => 'api' do
match '*', :action => 'cors', :constraints => { :method => 'OPTIONS' }
end
# base_api_controller.rb:
class Api::BaseApiController < ApplicationController
def cors
# ... setting headers of Access-Control-Allow-Origin and stuff here...
end
end
The problem I am running into is when I make a request via javascript I get an error:
OPTIONS <url> Resource failed to load
This seems like it should work and I just missed something simple. Any ideas?
+3
source to share
1 answer
I'm not sure why you want requests to go through an "action controller" rather than the default api / controller, but here's how you could do it
#Gemfile
gem 'rack-cors', :require => 'rack/cors'
#config/application.rb
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins "*"
resource "/api/*", :headers => :any, :methods => [:options], :action => 'cors'
end
end
Alternatively, I would not dispatch this to another action with a controller , so this is indeed what I think you want
#Gemfile
gem 'rack-cors', :require => 'rack/cors'
#config/application.rb
config.middleware.insert_before 0, "Rack::Cors" do
allow do
origins "*"
resource "/api/*", :headers => :any, :methods => [:options]
end
end
+1
source to share