Chrome将Origin标头添加到同源请求

时间:2023-04-18
本文介绍了Chrome将Origin标头添加到同源请求的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着跟版网的小编来一起学习吧!

问题描述

我们正在向本地运行的服务器发布 AJAX 请求,即

We're POSTing an AJAX request to a server running locally, i.e.

xhr.open("POST", "http://localhost:9000/context/request");
xhr.addHeader(someCustomHeaders);
xhr.send(someData);

这个 javascript 正在执行的页面也是从 localhost:9000 提供的,也就是说,这看起来完全像一个同源请求.

The page that this javascript is being executed is also being served from localhost:9000, i.e. this totally looks like a same-origin request.

但是,由于某种原因,谷歌浏览器总是在结果请求中设置一个 Origin 标头,导致我们的服务器基于错误假设它是 CORS 请求而阻止该请求.

However, for some reason, Google Chrome always sets an Origin header in the resulting request, causing our server to block the request based on the false assumption that it's CORS request.

这在 Firefox 中不会发生.

This does not happen in Firefox.

此外,Firefox 和 Chrome 都没有发送 OPTIONS 预检请求,这令人困惑;为什么在没有预先检查的情况下设置 Origin 标头以确保服务器允许 Origin 和 Custom 标头?

Also, neither Firefox nor Chrome are sending an OPTIONS preflight request, which is confusing; why set an Origin header without first preflighting to make sure the the Origin and the Custom headers are allowed by the server?

有谁知道这种情况下发生了什么?我们是否误解了 CORS 规范?

Does anyone know what is going on in this case? Are we misunderstanding the CORS spec?

推荐答案

Chrome 和 Safari 在同源 POST/PUT/DELETE 请求中包含 Origin 标头(同源 GET 请求不会有Origin 标头).Firefox 在同源请求中不包含 Origin 标头.浏览器不期望同源请求上的 CORS 响应标头,因此对同源请求的响应将发送给用户,无论它是否具有 CORS 标头.

Chrome and Safari include an Origin header on same-origin POST/PUT/DELETE requests (same-origin GET requests will not have an Origin header). Firefox doesn't include an Origin header on same-origin requests. Browsers don't expect CORS response headers on same-origin requests, so the response to a same-origin request is sent to the user, regardless of whether it has CORS headers or not.

我建议检查 Host 标头,如果它与 Origin 标头中的域匹配,则不要将请求视为 CORS.标题看起来像这样:

I would recommend checking the Host header, and if it matches the domain in the Origin header, don't treat the request as CORS. The headers look something like this:

Host: example.com
Origin: http://example.com

请注意,Origin 将有方案 (http/https)、域和端口,而 Host 将只有域和端口.

Note that Origin will have the scheme (http/https), domain and port, while Host will only have the domain and port.

这篇关于Chrome将Origin标头添加到同源请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

上一篇:ReactJS API 数据获取 CORS 错误 下一篇:Express JS:请求的资源上不存在“Access-Control-Allow-Origin"标头

相关文章