问题
I am on Rails5 and I want to allow CORS on one of my route. Here is how I can allow CORS for all my route, but is there a way to only whitelist for one endpoint?
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '*', :headers => :any, :methods => [:get, :post, :options]
end
end
回答1:
To allow cross-origin requests for only a particular endpoint path, use it as the first resource
arg:
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '/endpoint/to/allow', :headers => :any, :methods => [:get, :post, :options]
end
end
That’ll allow cross-origin requests only for the path /endpoint/to/allow
.
If you want to allow multiple paths, you can specify multiple resource
declarations:
config.middleware.insert_before 0, Rack::Cors do
allow do
origins '*'
resource '/endpoint/to/allow', :headers => :any, :methods => [:get, :post, :options]
resource '/another/endpoint/', :headers => :any, :methods => [:get, :post, :options]
end
end
https://github.com/cyu/rack-cors#resource has more details.
来源:https://stackoverflow.com/questions/43427080/how-to-enable-cors-for-only-selected-route-rails