htmlcross-domainsame-origin-policyaccess-controlcors

How do I use Access-Control-Allow-Origin? Does it just go in between the html head tags?


I've been reading about Access-Control-Allow-Origin because it seems effective at allowing cross domain requests since I have access to the external site. My question ism how do I use Access-Control-Allow-Origin to allow cross domain requests. I tried this (don't laugh) (by the way all I want is for a single number, 1 or 0 to be returned)

<html>
<head>
Access-Control-Allow-Origin: *
</head>
<body>
1
</body>
</html>

Am I close? Thanks for your help. If there is an easier way to do a simple cross-domain request let me know.


Solution

  • That is an HTTP header. You would configure your webserver or webapp to send this header ideally. Perhaps in htaccess or PHP.

    Alternatively you might be able to use

    <head>...<meta http-equiv="Access-Control-Allow-Origin" content="*">...</head>
    

    I do not know if that would work. Not all HTTP headers can be configured directly in the HTML.

    This works as an alternative to many HTTP headers, but see @EricLaw's comment below. This particular header is different.

    Caveat

    This answer is strictly about how to set headers. I do not know anything about allowing cross domain requests.

    About HTTP Headers

    Every request and response has headers. The browser sends this to the webserver

    GET /index.htm HTTP/1.1
    

    Then the headers

    Host: www.example.com
    User-Agent: (Browser/OS name and version information)
    .. Additional headers indicating supported compression types and content types and other info
    

    Then the server sends a response

    Content-type: text/html
    Content-length: (number of bytes in file (optional))
    Date: (server clock)
    Server: (Webserver name and version information)
    

    Additional headers can be configured for example Cache-Control, it all depends on your language (PHP, CGI, Java, htaccess) and webserver (Apache, etc).