如何仅对选定的路线导轨启用CORS [英] How to enable CORS for only selected route rails

查看:100
本文介绍了如何仅对选定的路线导轨启用CORS的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在Rails5上,并且我希望在我的一条路线上允许CORS.这是我可以为所有路由允许CORS的方法,但是有没有办法只将一个端点列入白名单?

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

推荐答案

要仅对特定端点路径允许跨域请求,请将其用作第一个resource arg:

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

这将仅允许对路径/endpoint/to/allow进行跨域请求.

That’ll allow cross-origin requests only for the path /endpoint/to/allow.

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

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 具有更多细节.

这篇关于如何仅对选定的路线导轨启用CORS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆