Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
136 views
in Technique[技术] by (71.8m points)

javascript - Chrome adding Origin header to same-origin request

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);

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.

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.

This does not happen in Firefox.

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?

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

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

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...