1

I read that the main idea behind the browser security policy is that you can't retrieve data from a domain that is different from the domain the page itself was served from. But I don't understand why I can do this then?

<!doctype html>
<html>
    <head>
        <title>Template</title>
        <meta charset="utf-8">
        <link rel="stylesheet" href="style.css">
        <script src="jscript.js"></script>
    </head>
    <body>
    </body>
</html>

window.onload = function() {
    var request = new XMLHttpRequest();
    var url = "http://mbigras.github.io/geolocation/data.json";
    request.open("GET", url);

    request.onload = function() {
        if (request.status == 200) {
            var object2 = JSON.parse(request.responseText);
            alert(object2.name + ", age " + object2.age);
        }
    }
    request.send(null);
};

Because isn't the the page being served from my computer at home (index.html on my local machine) while I'm using XMLHttpRequest to request json data from github? Or am I misunderstanding something here?

mbigras
  • 7,664
  • 11
  • 50
  • 111

1 Answers1

2

This is called the cross origin policy. The host of the content (in this case github) can send HTTP headers back to your script that say "hey, you're allowed to do cross origin requests to me!". Your web browser (being compliant with the same origin policy) will then allow the request to happen.

It's actually your browser (not the github server) that ultimately throws away a cross origin request. Even when you make an AJAX request to a location that does not allow cross origin requests, your browser is still performing a request (known as an preflight request).

Before the actual requests fires off, your browser does a preflight request to the remote server to check and see if you're allowed to perform cross origin requests. Your browser says to the remote server: "hey, am I allowed to do requests to you given that you're on another domain?" if the web server running on the other end doesn't reply with cross origin headers then the answer is no.

In the case with the github url you've referenced, github's web server IS replying with cross origin headers and so your browser says "great, thanks!" and executes the GET or POST request as you would expect.

An example of cross origin headers that a server may send to a client could be:

Access-Control-Allow-Origin: http://bob.com
Access-Control-Allow-Methods: GET, POST, PUT
Content-Type: text/html; charset=utf-8

and in this example, the server is telling the client "requests from bob.com are allowed, so long as they're GET, POST OR PUT requests"

David Zorychta
  • 13,039
  • 6
  • 45
  • 81