How to enable CORS for only selected route rails

六月ゝ 毕业季﹏ 提交于 2019-12-10 15:23:52

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!