javascript - 如果我在使用 cors 时添加标准的 http header ,为什么请求会被预检?

标签 javascript http cors preflight custom-headers

我需要添加一些常见的额外信息(需要与我们的大多数 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”标题仍然触发选项请求。

所以我有两个问题:

  1. 为什么标准的 http header 会触发预检请求?
  2. 我应该如何在不触发预检请求的情况下发送额外信息?

任何帮助将不胜感激。

最佳答案

阅读同一页面的以上部分,了解什么构成了不需要预检的“简单请求”:

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/

相关文章:

javascript - 如何使用纯javascript在屏幕上平滑地拖动图像

.net - vue 和 dotnet 的 cors 问题

java - 从 dropbox url 下载忽略范围

api - 如何设计仅进行数据转换的 REST 调用?

azure - 以编程方式从事件网格触发的函数中获取函数应用程序 url

java - RESTful 网络服务 : how to set headers in java to accept XMLHttpRequest allowed by Access-Control-Allow-Origin

javascript - 为什么 CORS 允许向任何服务器发送数据?

javascript - Jquery:寄存器打开之前的时间计数器

javascript - 在 iPhone 网络应用程序中播放声音

javascript - 穿过充满物体的物体