Search code examples
javascriptajaxcross-domainsame-origin-policycross-domain-policy

Why do browser blocks specific Ajax requests?


I have two code snippets:

$.getJSON("https://noembed.com/embed", {"format": "json", "url": input.val()}, function (data) {
// work with data
});

The second one:

$.getJSON("https://www.youtube.com/oembed", {"format": "json", "url": input.val()}, function (data) {
// work with data
});

The first one will be successful, but the second one not. They were both sent from http://localhost:8080/myapp/page. Why does the same origin policy not permit both requests? (Actually it's question about browsers).


Solution

  • Some servers permit browsers to do cross origin requests, some do not. See CORS.

    There can be multiple CORS headers involved, so either none of them are present or something required for this particular operation is missing from YouTube. But, the point is that the server decides if it wants to permit cross origin operations from browsers and thus your two servers are offering different capabilities in this regard.

    This particular youtube API is a bit suspect though because it exists purely for cross-origin reasons so there must be something else going on that is preventing it from working. To learn more, one would have to look at the network trace to see exactly what was being sent to youtube, what CORS headers were present and perhaps what exactly might be causing this. Could, for example, there be an http/https mismatch and that's why CORS is failing?