【问题标题】:How to enable CORS for only selected route rails如何仅为选定的路线启用 CORS
【发布时间】:2017-04-15 14:11:53
【问题描述】:

我在 Rails5 上,我想在我的一条路线上允许 CORS。以下是我如何允许我的所有路由使用 CORS,但有没有办法只为一个端点加入白名单?

    config.middleware.insert_before 0, Rack::Cors do
      allow do
        origins '*'
        resource '*', :headers => :any, :methods => [:get, :post, :options]
      end
    end

【问题讨论】:

    标签: ruby-on-rails cors rack-cors


    【解决方案1】:

    要只允许对某个端点路径的跨域请求,请将其用作第一个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
    

    这将只允许路径 /endpoint/to/allow 的跨域请求。

    如果要允许多个路径,可以指定多个resource声明:

    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 有更多详细信息。

    【讨论】:

      猜你喜欢
      • 2020-08-04
      • 2019-08-27
      • 2017-05-30
      • 1970-01-01
      • 2015-08-08
      • 2019-06-28
      • 1970-01-01
      • 2014-01-19
      • 2015-08-13
      相关资源
      最近更新 更多