問題描述
我們正在向本地運行的服務器發布 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標頭添加到同源請求的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!