如何使用Rack compatitable application设置多个Access-Control-Allow-Origin
标头。
规范说我应该返回[status, headers, body]
数组。标题是标题:)的哈希。所以我不能两次设置相同的标题。
headers = {}
headers["Access-Control-Allow-Origin"] = "http://my.domain1.com"
headers["Access-Control-Allow-Origin"] = "http://my.domain2.com"
永远不会奏效。
我的情况怎么办?如何发送两个相同的标题?
答案 0 :(得分:1)
使用数组散列非常常见,所以请尝试:
headers = {
"Access-Control-Allow-Origin" => %w[
http://my.domain1.com
http://my.domain2.com
]
}
我猜测它应该是
{ "Access-Control-Allow-Origin" => [ 'a', 'b' ] * "\n" }
查看the RFC,相关部分为“5.1 Access-Control-Allow-Origin Response Header”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
所以,试试:
[ 'a', 'b' ] * ";"
%w[a b].join(';')
答案 1 :(得分: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