AJAX request gets "No 'Access-Control-Allow-Origin' header is present on the requested resource" error

65,944

Solution 1

This is by design. You can't make an arbitrary HTTP request to another server using XMLHttpRequest unless that server allows it by putting out an Access-Control-Allow-Origin header for the requesting host.

https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS

You could retrieve it in a script tag (there isn't the same restriction on scripts and images and stylesheets), but unless the content returned is a script, it won't do you much good.

Here's a tutorial on CORS:

http://www.bennadel.com/blog/2327-cross-origin-resource-sharing-cors-ajax-requests-between-jquery-and-node-js.htm

This is all done to protect the end user. Assuming that an image is actually an image, a stylesheet is just a stylesheet and a script is just a script, requesting those resources from another server can't really do any harm.

But in general, cross-origin requests can do really bad things. Say that you, Zoltan, are using coolsharks.com. Say also that you are logged into mybank.com and there is a cookie for mybank.com in your browser. Now, suppose that coolsharks.com sends an AJAX request to mybank.com, asking to transfer all your money into another account. Because you have a mybank.com cookie stored, they successfully complete the request. And all of this happens without your knowledge, because no page reload occurred. This is the danger of allowing general cross-site AJAX requests.

If you want to perform cross-site requests, you have two options:

  1. Get the server you are making the request to to either
    a. Admit you by putting out a Access-Control-Allow-Origin header that includes you (or *)
    b. Provide you with a JSONP API.

or

  1. Write your own browser that doesn't follow the standards and has no restrictions.

In (1), you must have the cooperation of the server you are making requests to, and in (2), you must have control over the end user's browser. If you can't fulfill (1) or (2), you're pretty much out of luck.

However, there is a third option (pointed out by charlietfl). You can make the request from a server that you do control and then pass the result back to your page. E.g.

<script>
$.ajax({
    type: 'GET',
    url: '/proxyAjax.php?url=http%3A%2F%2Fstackoverflow.com%2F10m',
    dataType: 'text/html',
    success: function() { alert("Success"); },
    error: function() { alert("Error"); }
});
</script>

And then on your server, at its most simple:

<?php
// proxyAjax.php
// ... validation of params
// and checking of url against whitelist would happen here ...
// assume that $url now contains "http://stackoverflow.com/10m"
echo file_get_contents($url);

Of course, this method may run into other issues:

  • Does the site you are a proxy for require the correct referrer or a certain IP address?
  • Do cookies need to be passed through to the target server?
  • Does your whitelist sufficiently protect you from making arbitrary requests?
  • Which headers (e.g. modify time, etc) will you be passing back to the browser as your server received them and which ones will you omit or change?
  • Will your server be implicated as having made a request that was unlawful (since you are acting as a proxy)?

I'm sure there are others. But if none of those issues prevent it, this third method could work quite well.

Solution 2

you can ask the developers of that domain if they would set the appropriate header for you, this restriction is only for javascript, basically you can request the ressource from your server with php or whatever and the javascript requests the data from your domain then

Share:
65,944
Zoltán Schmidt
Author by

Zoltán Schmidt

Enthusiastic programmer, mostly interested in web development (working with Django, used to do NodeJS and PHP) and hobbyist of video game design. Former student at the Unversity of Pécs; currently working in Budapest. Programming is one of the biggest passions of my life. You can find me on LinkedIn and Gitlab. Also interested in: game modding and level design worldbuilding heavy metal and synthwave anime &amp; manga subculture astronomy &amp; space technology

Updated on July 09, 2022

Comments

  • Zoltán Schmidt
    Zoltán Schmidt almost 2 years

    I attempt to send a GET request in a jQuery AJAX request.

    $.ajax({
        type: 'GET',
        url: /* <the link as string> */,
        dataType: 'text/html',
        success: function() { alert("Success"); },
        error: function() { alert("Error"); },
    });
    

    However, whatever I've tried, I got XMLHttpRequest cannot load <page>. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:7776' is therefore not allowed access.

    I tried everything, from adding header : {} definitions to the AJAX request to setting dataType to JSONP, or even text/plain, using simple AJAX instead of jQuery, even downloading a plugin that enables CORS - but nothing could help.

    And the same happens if I attempt to reach any other sites.

    Any ideas for a proper and simple solution? Is there any at all?

  • Zoltán Schmidt
    Zoltán Schmidt over 8 years
    Does that help if - in this particular case - I authenticate myself via the SE API?
  • charlietfl
    charlietfl over 8 years
    missing #3 which is use a proxy on domain you do control to make request and return wanted resource
  • charlietfl
    charlietfl over 8 years
    and then there are 3rd party proxies like Yahoo YQL
  • Zoltán Schmidt
    Zoltán Schmidt over 8 years
    Thank you for the explanation! Does it mean that (if I don't want to use a proxy, then) my only method in any cases if I get a JSONP API?
  • Chris Middleton
    Chris Middleton over 8 years
    @Zoltan. Yes, without using a proxy, getting a JSONP API would be your best shot when trying to request pages from a popular site. (They're not likely to put your origin or * in their headers.) Keep in mind however that a JSONP API is not generally created for just requesting arbitrary navigable pages of a site (such as the "/10m" link in your question.). It's typically used where you would be receiving JSON, not HTML.
  • Zoltán Schmidt
    Zoltán Schmidt over 8 years
    Therefore, there are sites that I won't ever be able to GET under no circumstances, am I right? Without proxy of course.
  • john Smith
    john Smith over 8 years
    i dont know this api, but if the provider is providing an api for javascript usuage most propably they will offer one that will work with js request