【发布时间】:2015-02-06 15:05:59
【问题描述】:
我们在我们的网站上看到了众所周知的 CORS 错误:
XMLHttpRequest 无法加载 https://my-site.com/api。请求的资源上不存在“Access-Control-Allow-Origin”标头。 Origin 'https://my-other-site.com' 因此不允许访问。
问题是,Access-Control-Allow-Origin 在预检请求中设置正确...
OPTIONS https://my-site.com/api HTTP/1.1
Host: my-site.com
Access-Control-Request-Method: POST
Origin: https://my-other-site.com
Access-Control-Request-Headers: my-custom-header, accept, content-type
Accept: */*
Referer: https://my-other-site.com/
...other stuff...
HTTP/1.1 200 OK
Access-Control-Allow-Origin: https://my-other-site.com
Access-Control-Allow-Methods: POST
Access-Control-Allow-Headers: my-custom-header, accept, content-type
Access-Control-Expose-Headers: my-custom-header
...other stuff...
...但是,它没有在后续请求中设置。
POST https://my-site.com/api HTTP/1.1
Host: my-site.com
Accept: */*
My-Custom-Header: abcd123
Origin: https://my-other-site.com
Referer: https://my-other-site.com/
...other stuff...
HTTP/1.1 200 OK
My-Custom-Header: abcd123
...other stuff...
我不明白这个问题。根据我在网上阅读的一切,如果我们使用预检请求,我们不需要为实际请求添加 CORS 标头。但是,显然情况并非如此。
所有示例here 和here 在实际响应中都包含Access-Control-Allow-Origin 标头,但不包含任何其他“必需” CORS 标头。当我们将那个标头添加到我们的实际响应中时,错误就消失了。
所以我的问题是,两个请求中实际上都需要 Access-Control-Allow-Origin 标头吗?这是在哪里说明的?为什么这是真的?
【问题讨论】:
标签: javascript security web cors