Why am I seeing an "origin is not allowed by Access-Control-Allow-Origin" error here? [duplicate]
Asked Answered
M

11

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?

Mosira answered 16/2, 2012 at 11:1 Comment(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.Cleaves
C
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!

Cleaves answered 16/2, 2012 at 12:51 Comment(5)
Thanks! I didn't know that this would happen in the same host but in a different port.Horning
Can I use AmplifyJS to send to a differnt domain ?Hydria
I never used AmplifyJS si i don't know. If it is only a Javascript library (as jQuery) i highly doubt you can avoid jsonp. If it has a server part too it could still be possible. I can't say more, sorry.Cleaves
Doesn't jsonp only work for GET requests?Smote
In my case I was trying to connect to a different database in the EF connection string resulting in the CORS error (ASP.NET Web API)Orthopsychiatry
A
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

Archives answered 17/2, 2012 at 11:34 Comment(11)
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.Quietude
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?Lepanto
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.Archives
do we need to make change in httpd.conf file or php.ini file ?Lyon
You should add it to your Ajax responses only. Here is how you would add a header in PHP: header('Access-Control-Allow-Origin: *');Archives
@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?Litigant
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!Bentley
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.Archives
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?Ghent
@FedericoCapaldo in that case you would create your own API, acting as a proxy, to forward the requests to the original API.Archives
see https://mcmap.net/q/46866/-how-to-bypass-access-control-allow-origin for a PHP exampleBernt
B
38

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

Benoit answered 20/7, 2012 at 2:36 Comment(4)
Which you certainly only want to do for development purposes, never when surfingVaccaro
Agreed @Vaccaro and updated my answer.Benoit
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.Prospect
how do you enable it back? (how to go backwards?)Levalloisian
S
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)
{
}
Sherasherar answered 14/12, 2012 at 11:52 Comment(3)
Why did people downvote this? This is a way to achieve this in ASP.netCumming
I tried this, But didn't worked. still getting the error. using MVC5Picaroon
Adding in 'Application_BeginRequest' will allow cross calls to all methods of API. What if I want to do it for a single web-method?Blowing
D
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>
Dewain answered 8/11, 2013 at 5:50 Comment(0)
K
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
Kare answered 19/7, 2013 at 14:14 Comment(0)
R
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 "*"
Rosanarosane answered 2/5, 2016 at 15:11 Comment(0)
R
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

Reducer answered 17/12, 2014 at 15:48 Comment(0)
P
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=?

Preshrunk answered 25/9, 2012 at 20:16 Comment(1)
The magic parameter could have other names as well. Documentation: api.jquery.com/jQuery.getJSON/#jsonpBrewster
U
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!!

Unbonnet answered 9/1, 2013 at 14:27 Comment(0)
T
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).

Teferi answered 30/5, 2015 at 11:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.