CORS and Origin header?

后端 未结 2 1249
长发绾君心
长发绾君心 2020-12-13 04:08

When we need to invoke an Ajax request we do :

if(typeof XMLHttpRequest !== \'undefined\') xhr = new XMLHttpRequest();
else
{
    var versions = [\"Microsof         


        
相关标签:
2条回答
  • 2020-12-13 05:11

    The Origin header

    When this header is added ?

    During the header's stage, before the document's body is sent (after open, before send).

    Is it added when a browser (that support CORS) is doing a request ? ( cross domain or non-cross-domain?)

    It is added when the origin doesn't match the page from which the XMLHttpRequest is created, but may also be sent in a same-origin request.

    Or does it added automatically when the browser "sees" that the request target origin is different from the current origin...

    Yes.

    However, the browser will always send the required Origin headers when necessary.

    This is part of the XMLHttpRequest spec; if you're making a cross-domain request, in the request headers an extra header is sent. This header is e.g. Origin: http://www.stackoverflow.com and is appended by a standards-following browser without user interaction.


    You can read more on the specification in MozillaWiki's Security section, WHATWG and html5.org. It is implemented by (that I know of) FireFox and Google Chrome. I don't believe it is part of W3C yet. Further do not assume the origin header is true, as it can be set manually by modified borwsers or other software.

    0 讨论(0)
  • 2020-12-13 05:12

    The origin header is added automatically (generally) when you do a cross domain request.

    To test it, I opened the console on this page and made two different requests: one for another domain and one for '/' and just the first got the origin header added.

    BTW, I'm using JQuery for it and I'd really advise you to use it too in order to have the same behavior cross-browser.

    For complementary info on the subject, check this:

    The first thing to note is that a valid CORS request always contains an Origin header. This Origin header is added by the browser, and can not be controlled by the user. The value of this header is the scheme (e.g. http), domain (e.g. bob.com) and port (included only if it is not a default port, e.g. 81) from which the request originates; for example: http://api.alice.com.

    The presence of the Origin header does not necessarily mean that the request is a cross-origin request. While all cross-origin requests will contain an Origin header, some same-origin requests might have one as well. For example, Firefox doesn't include an Origin header on same-origin requests. But Chrome and Safari include an Origin header on same-origin POST/PUT/DELETE requests (same-origin GET requests will not have an Origin header).

    Source

    0 讨论(0)
提交回复
热议问题