我需要添加一些常见的额外信息(需要与我们的大多数 http 请求一起发送)以跨域 http 请求,额外数据类似于设备信息或位置信息。我们目前为这些信息使用自定义的 http header ,但自定义 header 会使浏览器在真正的 http 请求之前发送预检请求,因此出于性能考虑,我们希望删除预检请求。我们首先考虑使用cookie,但是由于请求是跨域的,我们不能用javascript为我们API的域设置cookie。然后我搜索了文档,根据Mozilla docs :
In particular, a request is preflighted if:
It uses methods other than GET, HEAD or POST. Also, if POST is used to send request data with a Content-Type other than application/x-www-form-urlencoded, multipart/form-data, or text/plain, e.g. if the POST request sends an XML payload to the server using application/xml or text/xml, then the request is preflighted.
It sets custom headers in the request (e.g. the request uses a header such as X-PINGOTHER)
所以我想如果我使用 standard http header很少使用:“From”标题,它不会触发选项请求。但是在我测试之后,我发现我错了,“From”标题仍然触发选项请求。
所以我有两个问题:
- 为什么标准的 http header 会触发预检请求?
- 我应该如何在不触发预检请求的情况下发送额外信息?
任何帮助将不胜感激。
最佳答案
阅读同一页面的以上部分,了解什么构成了不需要预检的“简单请求”:
Apart from the headers set automatically by the user-agent (e.g.
Connection
,User-Agent
, etc.), the only headers which are allowed to be set manually are
Accept
Accept-Language
Content-Language
Content-Type
“自定义 header ”不是指“非标准 header ”,它是指除这四个之外的任何不由浏览器自动设置的 header 。
关于javascript - 如果我在使用 cors 时添加标准的 http header ,为什么请求会被预检?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34080346/