我怎么知道哪个 access-control-allow-headers 允许 CORS?

How do I know which access-control-allow-headers to allow for CORS?

鉴于这些要求 headers:

Host: api.example.org
User-Agent: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.11; rv:41.0) Gecko/20100101 Firefox/41.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
DNT: 1
Origin: https://web.example.org
Access-Control-Request-Method: GET
Access-Control-Request-Headers: authorization
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache

这些响应 headers:

Connection: keep-alive
Content-Length: 0
Content-Type: text/plain; charset=utf-8
Date: Tue, 13 Oct 2015 10:57:34 GMT
Server: nginx/1.8.0
access-control-allow-headers: Authorization, Content-Type
access-control-allow-methods: PUT, DELETE, PATCH
access-control-allow-origin: *

即使只有 AuthorizationContent-Type headers 被明确允许,这仍然有效。为什么我不必允许我的浏览器发送的其他 headers? (例如 DNT


更新this MDN page包含简单headers的概述(默认CORS-safelisted请求headers):

A simple header (or CORS-safelisted request header) is one of the following HTTP headers:

  • Accept
  • Accept-Language
  • Content-Language
  • Content-Type with a MIME type of its parsed value (ignoring parameters) of either application/x-www-form-urlencoded, multipart/form-data, or text/plain.

Or one of these client hint headers:

  • DPR
  • Downlink
  • Save-Data
  • Viewport-Width
  • Width

没有看到你生成 headers 的代码,也没有看到你在哪个系统上提供服务,即 nginx 或 apache,我能做的最好的事情就是让你参考 http://client.cors-api.appspot.com/client which will allow you to test your CORS requests. Also, you should look at http://enable-cors.org/server.html 来了解你的具体设置.例如在 nginx 上,你可以有这样的东西

add_header 'Access-Control-Allow-Headers' 'DNT,X-CustomHeader,Keep-Alive,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type';

有一组正常的headers,然后是headers的一组你要显式调出。请参阅 http://www.html5rocks.com/en/tutorials/cors/#toc-adding-cors-support-to-the-server 关于在服务器上进行设置的信息。

Access-Control-Allow-Headers 由后端附加,您无法控制客户端的 header。Access-Control-Allow-Headers 应在响应中返回 object。

因此,要将其他 header 包含到 Access-Control-Allow-Headers header 中作为响应 object - 您必须配置您的 Web 服务器或更新后端应用程序来处理附加请求每个请求的期望值 Access-Control-Allow-Headers

要允许客户端请求中的任何 header,服务器应向每个响应添加 Access-Control-Allow-Origin: * header。

关于如何设置 CORS 以您想要的方式工作的文章和信息很多。例如那个 - Enabling CORS