Why am I seeing an "origin is not allowed by Access-Control-Allow-Origin" error here?

Muhammad Usman picture Muhammad Usman · Feb 16, 2012 · Viewed 433.1k times · Source

I am seeing the following error:

Origin http://localhost:8080 is not allowed by Access-Control-Allow-Origin

with this code:

var http = new getXMLHttpRequestObject();
var url = "http://gdata.youtube.com/action/GetUploadToken";
var sendXML = '<?xml version="1.0"?><entry xmlns="http://www.w3.org/2005/Atom"'+
    'xmlns:media="http://search.yahoo.com/mrss/'+
    'xmlns:yt="http://gdata.youtube.com/schemas/2007">'+
    '<media:group><media:title type="plain">My First API</media:title>'+
    '<media:description type="plain">First API</media:description>'+
    '<media:category scheme="http://gdata.youtube.com/schemas/2007/categories.cat">People</media:category>'+
    '<media:keywords>first, api</media:keywords></media:group></entry>';
http.open("POST", url, true);
http.setRequestHeader("Authorization", "AuthSub token=" + AccessToken);
http.setRequestHeader("X-GData-Key", "key="+ dev_key);
http.setRequestHeader("Content-Type", "application/atom+xml; charset=UTF-8");

http.onreadystatechange = function() {
    if(http.readyState == 4) {
        alert(http.responseXML);
    }
}
http.send(sendXML);

What can cause this, and how do I solve it?

Answer

andreapier picture andreapier · Feb 16, 2012

Javascript is limited when making ajax requests outside of the current domain.

  • Ex 1: your domain is example.com and you want to make a request to test.com => you cannot.
  • Ex 2: your domain is example.com and you want to make a request to inner.example.com => you cannot.
  • Ex 3: your domain is example.com:80 and you want to make a request to example.com:81 => you cannot
  • EX 4: your domain is example.com and you want to make a request to example.com => you can.

Javascript is limited by the "same origin policy" for security reasons so that a malicious script cannot contact a remote server and send sensitive data.

jsonp is a different way to use javascript. You make a request and results are encapsulated into a callback function which is run in the client. It's the same as linking a new script tag into the head part of your html (you know that you can load scripts from different domains than yours here).
However, to use jsonp the server must be configured properly. If this is not the case you cannot use jsonp and you MUST rely on a server side proxy (PHP, ASP, etc.). There are plenty of guides related to this topic, just google it!