Blu*_*eft 5 javascript security cors web
我们在我们的网站上看到了众所周知的CORS错误:
XMLHttpRequest无法加载https://my-site.com/api。所请求的资源上没有“ Access-Control-Allow-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...
Run Code Online (Sandbox Code Playgroud)
...但是,它没有在后续请求中设置。
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...
Run Code Online (Sandbox Code Playgroud)
我不明白这个问题。根据我在网上阅读的所有内容,如果我们使用预检请求,则无需为实际请求添加CORS标头。但是,事实显然并非如此。
此处和此处的所有示例均在Access-Control-Allow-Origin实际响应中包含标头,但不包含任何其他“必需” CORS标头。当我们在实际响应中添加一个标头时,错误就消失了。
所以我的问题是,是Access-Control-Allow-Origin在这两个请求,实际所需的头? 哪里写的?为什么会这样呢?
是的,似乎两个响应都应包含必要的 CORS 标头。
在Simple Cross-Origin Request和Cross-Origin Request with Preflight 中,“实际请求”遵循相同的行为,检查 CORS 标头而不考虑预检(分别为步骤 1 和步骤 3)。
给定资源的资源共享检查算法如下:
如果响应包含零个或多个
Access-Control-Allow-Origin标头值,则返回失败并终止此算法。[...]
预检请求只会阻止“实际请求”的开始。