【问题标题】:ruby on rails - rack-cors multiple origins with different resourcesruby on rails - rack-cors 具有不同资源的多个来源
【发布时间】:2017-05-26 03:41:43
【问题描述】:

我正在使用 rack-cors gem 在我的 rails 应用程序中实现 CORS,但我不确定如何为不同的来源定义不同的资源。

我需要这样的东西:

config.middleware.insert_before 0, Rack::Cors do

  allow do
    origins 'http://localhost:3000'
    resource '/api/*', headers: :any, methods: [:get, :post, :options, :put, :delete]
  end

  allow do
    origins 'http://localhost:6000'
    resource '*', headers: :any, methods: [:get, :post, :options, :put, :delete]
  end

end

因此它将允许“http://localhost:3000”仅访问 '/api/*' 并允许“http://localhost:6000”访问所有。有可能吗?

上面的代码是正确的代码/语法吗?

谢谢。

【问题讨论】:

  • 尝试从origins 中删除http://

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


【解决方案1】:

我知道这有点老了,但对于那些发现它的人,我只用 Rails 5.1.4 api 解决这个问题

-

起源

ENV['CORS_ORIGINS'] = 'https://domain.first.com, http://another.origin.io'

科斯

Rails.application.config.middleware.insert_before 0, Rack::Cors do
  allow do
    origins ENV['CORS_ORIGINS'].split(',').map { |origin| origin.strip }

    resource '*',
      headers: :any,
      methods: [:get, :post, :put, :patch, :delete, :options, :head]
  end
end

【讨论】:

  • 我没有得到你的答案,因为问题是如何限制不同的域访问不同的资源。我不确定您的示例是否可以完成这部分的工作>因此它将允许“localhost:3000”仅访问“/api/*”
  • 似乎origins 在我的情况下不喜欢数组。这种方法对我不起作用
  • origins 期望域是变量,而不是一个数组。
  • @zhongxiao37 感谢您的建议。这可能解释了我奇怪的情况。好吧,我们将那些允许的域定义为一个数组。如何正确地将数组传递给origins
【解决方案2】:

检查和测试后发现它是正确的语法。您可以根据需要添加任意数量的块:

allow do
    origins '[the domain]'
    resource '[the resource/directories]', headers: :any, methods: [:get, :post, :options, :put, :delete]
end

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-09-25
    • 2023-03-29
    • 1970-01-01
    • 1970-01-01
    • 2011-05-25
    • 2011-04-13
    • 2011-05-20
    相关资源
    最近更新 更多