2

如何Access-Control-Allow-Origin使用 Rack 兼容应用程序设置多个标头。

规范说我应该返回[status, headers, body]数组作为结果。标头是标头的散列:)。所以我不能两次设置相同的标题。

headers = {}
headers["Access-Control-Allow-Origin"] = "http://my.domain1.com"
headers["Access-Control-Allow-Origin"] = "http://my.domain2.com"

永远不会工作。

在我的情况下我应该怎么做?如何发送两个相同的标头?

4

2 回答 2

1

It's very common to use a hash of arrays so try:

headers = {
  "Access-Control-Allow-Origin" => %w[
    http://my.domain1.com
    http://my.domain2.com
  ]
}

I've got a guess that it should be { "Access-Control-Allow-Origin" => [ 'a', 'b' ] * "\n" }

Looking at the RFC, the pertinent part is "5.1 Access-Control-Allow-Origin Response Header" which points to:

The Origin header field has the following syntax:

origin              = "Origin:" OWS origin-list-or-null OWS
origin-list-or-null = %x6E %x75 %x6C %x6C / origin-list
origin-list         = serialized-origin *( SP serialized-origin )
serialized-origin   = scheme "://" host [ ":" port ]
                    ; <scheme>, <host>, <port> from RFC 3986

So, try:

[ 'a', 'b' ] * ";"

Or, for the uninitiated:

%w[a b].join(';')
于 2013-07-08T14:25:25.170 回答
0

根据https://www.w3.org/TR/cors/#access-control-allow-origin-response-header规范,Access-Control-Allow-Origin标头可能只有一个资源。

我已经通过自定义中间件解决了这种情况:

class CORS
  ORIGINS = %w[http://localhost:3001 http://localhost:3002].freeze

  # ...

  def call(env)
    @status, @headers, @response = @app.call(env)
    @headers['Access-Control-Allow-Origin'] = assign_allow_origin_header(env['HTTP_ORIGIN'])
    [@status, @headers, @response]
  end

  private

  def assign_allow_origin_header(origin)
    ORIGINS.include?(origin) ? origin : 'null'
  end
end
于 2017-12-28T16:24:47.047 回答