139

I'm using .htaccess to rewrite urls and I used html base tag in order to make it work.

Now, when I try to make an ajax request I get the following error:

XMLHttpRequest cannot load http://www.example.com/login.php. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://example.com' is therefore not allowed access.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
Th3lmuu90
  • 1,717
  • 2
  • 15
  • 18
  • 1
    Nevermind... it is working now, I don't even know what was the mistake :S – Th3lmuu90 Dec 06 '13 at 21:20
  • 8
    Altough subtle, `http://wordicious.com` is a **different domain** than `http://www.wordicious.com/`, thus the error. Btw, if it is working now and got back by itself, you should probably delete the question. – acdcjunior Dec 06 '13 at 21:33
  • @acdcjunior That seems to be the error, which is an astute observation on your part. If you post that as an answer I would upvote it. – Waleed Khan Dec 06 '13 at 21:55
  • 5
    It's a good thing the question wasn't deleted, or I wouldn't have seen it today! – icedwater May 18 '15 at 07:54

11 Answers11

170

Use addHeader Instead of using setHeader method,

response.addHeader("Access-Control-Allow-Origin", "*");

* in above line will allow access to all domains.


For allowing access to specific domain only:

response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");

Check this blog post.

Jaykumar Patel
  • 26,836
  • 12
  • 74
  • 76
  • 4
    it is showing addheader not defined. Can you please explain it? – Vaisakh Pc Oct 21 '14 at 07:42
  • 9
    Where do I put these lines? – DaveWalley Nov 24 '14 at 16:52
  • 14
    Where should this be added? – Alex Dec 29 '14 at 12:11
  • You can adding header to your response object. – Jaykumar Patel Dec 30 '14 at 05:34
  • 1
    That blog post is talking about Node.js and express. Not client side javascript. can anyone confirm if this works? – Sam Eaton Apr 20 '15 at 23:01
  • as mentioned above, please add more information about where to put these lines. – user137717 Sep 03 '15 at 03:45
  • 1
    I dont think this configuration can be done only on the client side.. So as to where to put it, it would be on the server side code (presumably when building a response to a request) – Chirag Ravindra Sep 16 '15 at 11:35
  • These lines must be put on the server-side code when building the response i guess. But it doesn't work on SparkJava-Server for me. http://sparkjava.com/documentation.html#request – kiltek Sep 18 '15 at 13:58
  • 1
    this works on spring-boot, java. For php is `header('Access-Control-Allow-Origin: *');`. This is a server side solution and not client side for those asking. If someone really wants to use CORS, is better to allow access for specific a domain, but I wouldn't recommend such a solution. Better implement an API or webservice and call it on your own application. – user2035693 Apr 05 '16 at 08:08
  • where does this go in Rails 5? – rigdonmr Oct 12 '16 at 22:33
147

Why the error is raised:

JavaScript code is limited by the same-origin policy, meaning, from a page at www.example.com, you can only make (AJAX) requests to services located at exactly the same domain, in that case, exactly www.example.com (not example.com - without the www - or whatever.example.com).

In your case, your Ajax code is trying to reach a service in http://wordicious.com from a page located at http://www.wordicious.com.

Although very similar, they are not the same domain. And when they are not on the same domain, the request will only be successful if the target's respose contains a Access-Control-Allow-Origin header in it.

As your page/service at http://wordicious.com was never configured to present such header, that error message is shown.

Solution:

As said, the origin (where the page with JavaScript is at) and the target (where the JavaScript is trying to reach) domains must be the exact same.

Your case seems like a typo. Looks like http://wordicious.com and http://www.wordicious.com are actually the same server/domain. So to fix, type the target and the origin equally: make you Ajax code request pages/services to http://www.wordicious.com not http://wordicious.com. (Maybe place the target URL relatively, like '/login.php', without the domain).



On a more general note:

If the problem is not a typo like the one of this question seems to be, the solution would be to add the Access-Control-Allow-Origin to the target domain. To add it, depends, of course, of the server/language behind that address. Sometimes a configuration variable in the tool will do the trick. Other times you'll have to add the headers through code yourself.

Community
  • 1
  • 1
acdcjunior
  • 132,397
  • 37
  • 331
  • 304
62

For .NET server can configure this in web.config as shown below

 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="your_clientside_websiteurl" />
     </customHeaders>
   </httpProtocol>
 </system.webServer>

For instance lets say, if the server domain is http://live.makemypublication.com and client is http://www.makemypublication.com then configure in server's web.config as below

 <system.webServer>
   <httpProtocol>
     <customHeaders>
       <add name="Access-Control-Allow-Origin" value="http://www.makemypublication.com" />
     </customHeaders>
  </httpProtocol>
 </system.webServer>
Steve
  • 546
  • 5
  • 18
Naga
  • 2,368
  • 3
  • 23
  • 33
23

If you get this error message from the browser:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin '…' is therefore not allowed access

when you're trying to do an Ajax POST/GET request to a remote server which is out of your control, please forget about this simple fix:

<?php header('Access-Control-Allow-Origin: *'); ?>

What you really need to do, especially if you only use JavaScript to do the Ajax request, is an internal proxy who takes your query and send it through to the remote server.

First in your JavaScript, do an Ajax call to your own server, something like:

$.ajax({
    url: yourserver.com/controller/proxy.php,
    async:false,
    type: "POST",
    dataType: "json",
    data: data,
    success: function (result) {
        JSON.parse(result);
    },
    error: function (xhr, ajaxOptions, thrownError) {
        console.log(xhr);
    }
});

Then, create a simple PHP file called proxy.php to wrap your POST data and append them to the remote URL server as a parameters. I give you an example of how I bypass this problem with the Expedia Hotel search API:

if (isset($_POST)) {
  $apiKey = $_POST['apiKey'];
  $cid = $_POST['cid'];
  $minorRev = 99;

  $url = 'http://api.ean.com/ean-services/rs/hotel/v3/list?' . 'cid='. $cid . '&' . 'minorRev=' . $minorRev . '&' . 'apiKey=' . $apiKey;

  echo json_encode(file_get_contents($url));
 }

By doing:

 echo json_encode(file_get_contents($url));

You are just doing the same query but on the server side and after that, it should works fine.

Nizar B.
  • 3,098
  • 9
  • 38
  • 56
10

You need to add this at start of your php page "login.php"

<?php header('Access-Control-Allow-Origin: *'); ?>
Shady Mohamed Sherif
  • 15,003
  • 4
  • 45
  • 54
7

you have to put the headers keys/values in options method response. for example if you have resource at http://mydomain.com/myresource then, in your server code you write

//response handler
void handleRequest(Request request, Response response) {
    if(request.method == "OPTIONS") {
       response.setHeader("Access-Control-Allow-Origin","http://clientDomain.com")
       response.setHeader("Access-Control-Allow-Methods", "GET,POST,PUT,DELETE,OPTIONS");
       response.setHeader("Access-Control-Allow-Headers", "Content-Type");
    }



}
i-systech.com
  • 71
  • 1
  • 2
3

The workaround is to use a reverse proxy running on your 'source' host and forwarding to your target server, such as Fiddler:

Link here: http://docs.telerik.com/fiddler/configure-fiddler/tasks/usefiddlerasreverseproxy

Or an Apache Reverse proxy...

Max O.
  • 528
  • 5
  • 14
hzrari
  • 1,803
  • 1
  • 15
  • 26
  • can this be done at an Apache or Nginx config level for a domain. e.g if a user is accessing mysite.com (no www) and the XHR is requesting www.mysite.com, can an htaccess or httpd.conf directive resolve this? – codecowboy Apr 02 '14 at 11:57
  • Sure, your Front-End App should behave as a reverse proxy. e.g for Apache, you have to install mod_proxy, and configure your rules using ProxyPassReverse (http://httpd.apache.org/docs/current/mod/mod_proxy.html#proxypassreverse). The same features seems to be availabe on Nginx also: http://wiki.nginx.org/LikeApache – hzrari Apr 02 '14 at 15:24
3

Basically alter API header response by adding following additional parameters.

Access-Control-Allow-Credentials: true

Access-Control-Allow-Origin: *

But this is not good solution when it comes to the security

Piusha
  • 594
  • 5
  • 11
3

Add this to you PHP file or main controller

header("Access-Control-Allow-Origin: http://localhost:9000");
Sam
  • 376
  • 3
  • 10
1

Solved with below entry in httpd.conf

#CORS Issue
Header set X-Content-Type-Options "nosniff"
Header always set Access-Control-Max-Age 1728000
Header always set Access-Control-Allow-Origin: "*"
Header always set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT,PATCH"
Header always set Access-Control-Allow-Headers: "DNT,X-CustomHeader,Keep-Alive,Content-Type,Origin,Authentication,Authorization,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control"
Header always set Access-Control-Allow-Credentials true

#CORS REWRITE
RewriteEngine On                  
RewriteCond %{REQUEST_METHOD} OPTIONS 
#RewriteRule ^(.*)$ $1 [R=200,L]
RewriteRule ^(.*)$ $1 [R=200,L,E=HTTP_ORIGIN:%{HTTP:ORIGIN}]]
Sandeep540
  • 897
  • 3
  • 13
  • 38
0

Pleaes find the Function used in XMLHTTPREQUEST in Javascript for setting up the request headers.

...

xmlHttp.setRequestHeader("Access-Control-Allow-Origin", "http://www.example.com");
...
</script>

Reference: https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/setRequestHeader