Solved thread

This post is marked as solved. If you think the information contained on this thread must be part of the official documentation, please contribute submitting a pull request to its repository.

No 'Access-Control-Allow-Origin' header is present on the requested resource

I have the following subdomain:

example.com
blog.example.com
forum.example.com
ajax.example.com

All the CNAME aliases are pointing to @.

The ajax.example.com is used to make the AJAX calls from any other page, for example from blog.example.com. There is of course a controller called AjaxController to handle the requests. Apache mod_headers is obviously enabled. In the HTML of blog.example.com, a click on a anchor tag triggers the following JavaScript code, making an AJAX call.

$(document).ready(
  function() {
    $("article > div.item-tools > a:first-child").click(
      function() {
        event.preventDefault();

        var postId = $(this).parents("article").attr("id");

        $.post('http://ajax.example.com/like/', {id: postId}, function(data) {
          $(this).addClass('active');
        });
      }
    );
  }
);

In the JavaScript console I see the following error:

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

XHR instead says:

Remote Address:77.72.53.198:80
Request URL:http://ajax.example.com/like/
Request Method:POST
Status Code:301 Moved Permanently
Request Headersview source
Accept:*/*
Accept-Encoding:gzip,deflate,sdch
Accept-Language:en-US,en;q=0.8,it;q=0.6,es;q=0.4
Connection:keep-alive
Content-Length:39
Content-Type:application/x-www-form-urlencoded; charset=UTF-8
Host:ajax.example.com
Origin:http://blog.example.com
Referer:http://blog.example.com/
User-Agent:Mozilla/5.0 (Macintosh; Intel Mac OS X 10_7_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36
Form Dataview sourceview URL encoded
id:46b076f8-81e6-437b-d515-81c03baeecdf
Response Headersview source
Connection:Keep-Alive
Content-Length:238
Content-Type:text/html; charset=iso-8859-1
Date:Tue, 08 Jul 2014 00:47:49 GMT
Keep-Alive:timeout=15, max=100
Location:http://example.com/like/
Server:Apache

I have tried to set Access-Control-Allow-Origin, because I know it's a problem related to CORS, but doesn't work.

header('Access-Control-Allow-Origin: *');

The fact is that I can't even debug, even if I put a breakpoint on the first line of the bootstrap php file. I have tried to set the Access-Control-Allow-Origin header in the httpd-vhosts.conf file, but nothing has changed. Any idea? I just need GET and POST methods, because I'm not making a REST service, and I want avoid JSONP. What can I try? Where can I put the header function call to make it work? I'm using Phalcon\MVC\Application class and not the Micro version.



82.2k

Access-Control-Allow-Origin must be set on the request, you have to make the request this way:

$.ajax({
    url: 'https://www.googleapis.com/moderator/v1/series?key='+key,
    data: myData,
    type: 'GET',
    crossDomain: true, // enable this
    dataType: 'jsonp',
    success: function() { alert("Success"); },
    error: function() { alert('Failed!'); },
    beforeSend: setHeader
});
edited Jul '14

@Phalcon no, that's not necessary, because I'm not making a JSONP request. I have created a stub, an empty project with just an home page. If you click on the picture of my cat and you look at your JavaScript console, you can see that works. I have just inserted in the afterExecuteRoute() the following line:

$this->response->setHeader('Access-Control-Allow-Origin', '*');

The problem is that the same code is not working on the main project I'm working on, and I'm still figuring why. But I'm optimist...

edited Jul '14

There is another interesting problem. If you load the home page everything works fine, but the monolog catch an exception:

[2014-07-08 21:07:13] ciripottolo.ERROR: Uncaught Exception Phalcon\Mvc\Dispatcher\Exception: "IndexController handler class cannot be loaded" at /Users/fff/Dropbox/Progetti/ciripottolo/bootstrap.php line 115 {"exception":"[object] (Phalcon\\Mvc\\Dispatcher\\Exception: IndexController handler class cannot be loaded at /Users/fff/Dropbox/Progetti/ciripottolo/bootstrap.php:115)"} []

I have the same problem on my main project, but the exception is raised only when I load a subdomain, ex. blog.myproject.com or forum.myproject.com. Instead on ciripottolo.com the exception is raised when I access the hope page. Do you have any idea?

This is the Apache Virtual Host configuration:

<VirtualHost *:80>
    ServerName ciripottolo.com
    ServerAlias ajax.ciripottolo.com www.ciripottolo.com blog.ciripottolo.com
    ServerAdmin [email protected]
    DocumentRoot "/opt/local/apache2/htdocs/ciripottolo.com"
    ErrorLog "/opt/local/apache2/logs/ciripottolo.com-error_log"
    CustomLog "/opt/local/apache2/logs/ciripottolo.com-access_log" common

    <Directory /opt/local/apache2/htdocs/ciripottolo.com>
        AuthType None
        AllowOverride all
        Order allow,deny
        Allow from all

        <IfModule rewrite_module>
            RewriteEngine on
            RewriteRule  ^$ public/    [L]
            RewriteRule  (.*) public/$1 [L]
        </IfModule>
    </Directory>

    <FilesMatch "\.(ttf|ttc|otf|eot|woff)$">
        <IfModule mod_headers>
            SetEnvIf Origin "^(.*\.?ciripottolo.com)$" ORIGIN_SUB_DOMAIN=$1
            Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
        </IfModule>
    </FilesMatch>

    <FilesMatch "(?i)\.php$">
        Order Allow,Deny
        Deny from all
    </FilesMatch>

    <FilesMatch "index\.php$">
        Order Allow,Deny
        Allow from all
    </FilesMatch>

    Alias /ciripottolo /Users/fff/Dropbox/Progetti/ciripottolo
    <Directory /Users/fff/Dropbox/Progetti/ciripottolo>
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>

OK, this is just ridicolous, I can't find an explanation. I have fixed that exception. In the stub project I was including in the index.volt a file that was missing. The error 500 probably was causing an exception inside Phalcon that reported that error. I have fixed the location of the JS file and the exception disappeared.

So I have removed from the real project html5shim.googlecode.com/svn/trunk/html5.js this JS and the exception disappeared. Then I have checked that the file exists, so I have included it again and monolog doesn't log any exception. How is that possible?



18.9k
Accepted
answer

It was an Apache configuration mistake. A stupid typo that I couldn't see. Solved.

i have same problem in django project.when i user $.get() function in chrome and safari ,it throw error "No 'Access-Control-Allow-Origin' header is present on the requested resource.". can u tell the solution , i really need it

Plese check this stub on github. It works.

I have the same problem here... do you remember what kind of configuration mistake did you make?

It was just a typo in the http-vhosts.conf file. A wrong letter in the site name. Checked many times but I coudln't see the mistake, because my mind was deceiving me. For the configuration, check this for the domain ciripottolo.com. You can find the stub link above. It's a Phalcon project that uses AJAX when you click on the cat image.

<VirtualHost *:80>
    ServerName www.ciripottolo.com
    Redirect permanent / http://ciripottolo.com/
</VirtualHost>

<VirtualHost *:80>
    ServerName ciripottolo.com
    ServerAlias ajax.ciripottolo.com www.ciripottolo.com blog.ciripottolo.com
    ServerAdmin [email protected]
    DocumentRoot "/opt/local/apache2/htdocs/ciripottolo.com"
    ErrorLog "/opt/local/apache2/logs/ciripottolo.com-error_log"
    CustomLog "/opt/local/apache2/logs/ciripottolo.com-access_log" common

    <Directory /opt/local/apache2/htdocs/ciripottolo.com>
        AuthType None
        AllowOverride all
        Order allow,deny
        Allow from all

        <IfModule rewrite_module>
            RewriteEngine on
            RewriteRule  ^$ public/    [L]
            RewriteRule  (.*) public/$1 [L]
        </IfModule>
    </Directory>

    <FilesMatch "\.(ttf|ttc|otf|eot|woff)$">
        <IfModule mod_headers>
            SetEnvIf Origin "^(.*\.?ciripottolo.com)$" ORIGIN_SUB_DOMAIN=$1
            Header set Access-Control-Allow-Origin "%{ORIGIN_SUB_DOMAIN}e" env=ORIGIN_SUB_DOMAIN
        </IfModule>
    </FilesMatch>

    <FilesMatch "(?i)\.php$">
        Order Allow,Deny
        Deny from all
    </FilesMatch>

    <FilesMatch "index\.php$">
        Order Allow,Deny
        Allow from all
    </FilesMatch>

    Alias /ciripottolo /Users/fff/Dropbox/Progetti/ciripottolo
    <Directory /Users/fff/Dropbox/Progetti/ciripottolo>
        Order allow,deny
        Allow from all
    </Directory>
</VirtualHost>