157

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?

sideshowbarker
  • 81,827
  • 26
  • 193
  • 197
Muhammad Usman
  • 10,426
  • 22
  • 72
  • 107
  • 1
    Are you sure that youtube entry point you are using is jsonp enabled? You cannot make ajax call to external domain, unless you use a server side proxy or a jsonp endpont. – andreapier Feb 16 '12 at 11:07

11 Answers11

172

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!

amit jha
  • 398
  • 2
  • 6
  • 22
andreapier
  • 2,958
  • 2
  • 38
  • 50
89

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

Sunny
  • 5,825
  • 2
  • 31
  • 41
  • 15
    If I understand this correctly, then the server of the API or remote resource (in this case the YouTube server) must set the header, i.e. it is the API hoster who must set this header, and not the API caller. – 0x4a6f4672 May 23 '12 at 13:15
  • 2
    Does anyone else find this confusing? Using Fiddler I can see a request being made and a valid result being returned... and then I get an exception. So the server doesn't seem to care at all. Yet the server is the one that needs configured? – Sailing Judo May 15 '13 at 14:21
  • 2
    Here the server doesn't care. It's the browser that tries to protect users by only letting back requests that are in the server's allow list. – Sunny May 17 '13 at 08:40
  • do we need to make change in httpd.conf file or php.ini file ? – Hitesh Mar 11 '14 at 11:28
  • You should add it to your Ajax responses only. Here is how you would add a header in PHP: `header('Access-Control-Allow-Origin: *');` – Sunny Mar 28 '14 at 11:49
  • @SailingJudo The server needs to be configured to tell the browser that it should allow this cross-domain resource. The browser enforces the same-origin policy, but the server tells the browser *how* and *when* to enforce it. The server can send a message that says, "Okay, browser, this time you can let JavaScript see the response." I've written about this in more detail in the end of the first section on my answer on [How does Access-Control-Allow-Origin header work?](http://stackoverflow.com/a/10636765/710446) – apsillers Mar 04 '15 at 14:14
  • Does it make sense? So I am a malware writer and set my own server with Allow-Origin: * and then I send my malicious script. What are they trying to protect here? It should be the client the one that decides what is legitimate and what is not, not the server! – user1156544 Nov 16 '16 at 15:25
  • It's preventing legitimate browsers from making unintended requests to legitimate servers. With this protection the browser can prevent malicious websites from doing ajax request on private URLs that should only be available to the current user. – Sunny Nov 18 '16 at 11:12
  • What if you are not the owner of the server? can you overcome this problem being the API caller without any power to change the server? – Fed May 19 '17 at 03:00
  • 1
    @FedericoCapaldo in that case you would create your own API, acting as a proxy, to forward the requests to the original API. – Sunny May 19 '17 at 15:41
  • see https://stackoverflow.com/a/17098221/3380951 for a PHP example – XoXo Sep 30 '17 at 08:44
38

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

Deqing
  • 14,098
  • 15
  • 84
  • 131
  • 52
    Which you certainly _only_ want to do for development purposes, _never_ when surfing – kynan Jul 27 '12 at 20:35
  • Agreed @kynan and updated my answer. – Deqing Nov 27 '12 at 14:07
  • wish I'd known this earlier today. for production deployment we use Nginx so its easiest to get that to handle the CORS headers, or they might be on the same domain:port anyway. its only for local dev that I wanted to bypass it. – Chris Sattinger Jul 05 '13 at 13:46
  • how do you enable it back? (how to go backwards?) – mike May 20 '17 at 23:01
10

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)
{
}
andr
  • 15,970
  • 10
  • 45
  • 59
Ammar Khan
  • 143
  • 1
  • 2
10

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>
Eric Leroy
  • 1,830
  • 1
  • 18
  • 31
8

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
Christian Müller
  • 869
  • 10
  • 17
5

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 "*"
Sireesh Yarlagadda
  • 12,978
  • 3
  • 74
  • 76
3

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

Meriam
  • 181
  • 2
  • 3
2

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=?

danwellman
  • 9,068
  • 8
  • 60
  • 88
  • 1
    The magic parameter could have other names as well. Documentation: http://api.jquery.com/jQuery.getJSON/#jsonp – Gruber Dec 14 '12 at 10:07
2

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!!

Saty
  • 1,068
  • 11
  • 24
0

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).

Wolfi
  • 1,331
  • 1
  • 11
  • 8