我正在构建一个网络 API。我发现每当我使用 Chrome 对我的 API 进行 POST、GET 时,总是在实际请求之前发送一个 OPTIONS 请求,这很烦人。目前,我让服务器忽略任何 OPTIONS 请求。现在我的问题是发送一个 OPTIONS 请求来加倍服务器的负载有什么好处?有什么办法可以完全阻止浏览器发送OPTIONS请求吗?
最佳答案
编辑 2018 年 9 月 13 日:添加了一些关于此飞行前请求的精确度以及在此响应末尾如何避免它。
OPTIONS
请求是我们在跨源资源共享 (CORS)
中所说的pre-flight
请求。
当您在特定情况下跨不同来源发出请求时,它们是必需的。
此飞行前请求是由某些浏览器作为安全措施发出的,以确保所完成的请求受到服务器的信任。 这意味着服务器了解请求中发送的方法、来源和 header 可以安全地采取行动。
每当您尝试执行跨源请求时,您的服务器不应忽略而是处理这些请求。
可以在这里找到很好的资源http://enable-cors.org/
处理这些问题的一种方法是确保对于任何带有 OPTIONS
方法的路径,服务器都会发送带有此 header 的响应
访问控制允许来源:*
这将告诉浏览器服务器愿意回答来自任何来源的请求。
有关如何将 CORS 支持添加到您的服务器的更多信息,请参阅以下流程图
http://www.html5rocks.com/static/images/cors_server_flowchart.png
编辑 2018-09-13
CORS OPTIONS
请求仅在某些情况下触发,如 MDN docs 中所述。 :
Some requests don’t trigger a CORS preflight. Those are called “simple requests” in this article, though the Fetch spec (which defines CORS) doesn’t use that term. A request that doesn’t trigger a CORS preflight—a so-called “simple request”—is one that meets all the following conditions:
The only allowed methods are:
- GET
- HEAD
- POST
Apart from the headers set automatically by the user agent (for example, Connection, User-Agent, or any of the other headers with names defined in the Fetch spec as a “forbidden header name”), the only headers which are allowed to be manually set are those which the Fetch spec defines as being a “CORS-safelisted request-header”, which are:
- Accept
- Accept-Language
- Content-Language
- Content-Type (but note the additional requirements below)
- DPR
- Downlink
- Save-Data
- Viewport-Width
- Width
The only allowed values for the Content-Type header are:
- application/x-www-form-urlencoded
- multipart/form-data
- text/plain
No event listeners are registered on any XMLHttpRequestUpload object used in the request; these are accessed using the XMLHttpRequest.upload property.
No ReadableStream object is used in the request.
关于http - 为什么会发送 OPTIONS 请求,我可以禁用它吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56893709/