Why am I seeing an “origin is not allowed by Access-Control-Allow-Origin” error here? [duplicate]


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?

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!


XMLHttpRequest will not let you reach localhost:8080 because of the "same origin policy".

You can allow requests from modern browsers by adding a header to your response on localhost:8080:

Access-Control-Allow-Origin: *

You can do so by adding directives to your HTTP server or adding headers via server-side code (PHP, Ruby, ...).

Read more on Cross-Origin ajax requests on https://developer.mozilla.org/en/http_access_control


If you are using Chrome, a simple workaround (only for development purposes) is to use option --disable-web-security.


Add a global.asax in your solution.

Add

HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");

in

protected void Application_BeginRequest(object sender, EventArgs e)
{
}

If your using apache, this works: put this in/create a .htaccess file in your public root, and add any other file extensions you might need.

<FilesMatch "\.(ttf|otf|eot|woff|jpg|png|jpeg|gif|js|json|html|css)$">
  <IfModule mod_headers.c>
    Header set Access-Control-Allow-Origin "*"
  </IfModule>
</FilesMatch>

For local development you can use a tool for modifying the HTTP response headers. For example Charles is able to do this by the included rewrite tool: Rewrite Tool

Just add a new rule for the target domain/location with:

Type: Add Header
Where: Response
Replace
     Name: Access-Control-Allow-Origin
     Value: *
Replace All

Here, we need to do two things for Apache Http

1) In httpd.config file, uncomment this file

LoadModule headers_module modules/mod_headers.so

2) Add this line at the bottom.

Header set Access-Control-Allow-Origin "*"

if you re using google chrome as a browser you can add CORS extension, and activate it , it will solve the hole problem without having to change anything in your code


Unrelated to this particular question, but for anyone in this situation using jQuery...This error is also caused if you try to make a JSONP request using jQuery and omit the magic callback parameter: callback=?


If you are from a java background one possible solution could be to make a servlet which calls the Web-services for your javascript. something like the below code in the GET(Your-choice) method...

JsonElement jelement;
    JsonArray jarray;
    try {
        URL url = new URL("http://rest."YOUR URL"#ba0482");
        URLConnection connection = url.openConnection();
        connection.setDoInput(true);
        InputStream inStream = connection.getInputStream();
        BufferedReader input = new BufferedReader(new InputStreamReader(inStream));

        jelement = new JsonParser().parse(input);

        jarray = jelement.getAsJsonArray();

        response.setContentType("application/json");
        PrintWriter out = response.getWriter();
        out.print(jarray);
        out.flush();
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

Now in the javascript simply specify the url as the servlet name!!


I run into the same error message, when using ajax to access a php page (javascript and php file are both located on same server).

The reason was that I specified the IP address as the domain in my JavaScript. This made the Browser believe that the call to the php file is on another server.

So an easy solution to get rid off this error message. a) verify javascript and php file are on the same server b) make sure the url (in particular the domain) in your JavaScript (e.g. http://www.smartana.co.uk/myJavaScript.js) ajax reflects your server url (e.g. http://www.smartana.co.uk/myServer.php).