Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any way to get past Access-Control-Allow-Origin for development on my own server?

I'm getting this JavaScript error

XMLHttpRequest cannot load http://foo.bar.no/API/map_tools/clean_addresses/check. Origin http://foo.bar.no:9294 is not allowed by Access-Control-Allow-Origin.

This is all on the same domain and the same server, but my JavaScript project is being hosted by a standalone server script that automatically bundles the JavaScript and it's dependencies into one file.

How do I get past this restriction while I'm developing?


I've tried allowing my JavaScript server script to connect. This is the result of a curl to the url:

HTTP/1.1 200 OK
Date: Wed, 11 Jan 2012 09:05:14 GMT
Server: Apache/2.2.16 (Debian)
Access-Control-Allow-Origin: http://foo.bar.no:9294
Vary: Accept-Encoding
Content-Length: 70
Content-Type: text/plain

array(1) {
  ["q"]=>
  string(31) "map_tools/clean_addresses/check"
}

And still I get the exact same error as I pasted above. Why does Chrome still refuse to connect to the damn URL when it's obviously allowed to!?

like image 457
Hubro Avatar asked Jan 11 '12 08:01

Hubro


3 Answers

OK I figured it out. I was looking for a simple and quick fix since I only need the cross domain requests for development purposes. Turns out that I just had to set both

header("Access-Control-Allow-Origin: http://foo.bar.no:9294");
header("Access-Control-Allow-Credentials: true");

In my PHP script on Apache. Then in my JavaScript code:

# Set jQuery ajax to use 'withCredentials' globally
$.ajaxSetup({
    xhrFields: {
        withCredentials: true
    }
});

And that did the trick

like image 62
Hubro Avatar answered Oct 03 '22 13:10

Hubro


Use your webserver's reverse proxy capabilities to proxy http://foo.bar.no/API/map_tools/clean_addresses/check to http://foo.bar.no:9294/API/map_tools/clean_addresses/check.

So, as you use Apache, you should add something like

    <Proxy *>
            Order allow,deny
            allow from all
    </Proxy>

    ProxyPass /API/map_tools/ http://foo.bar.no:9294/API/map_tools/
    ProxyPassReverse /API/map_tools/ http://foo.bar.no:9294/API/map_tools/

to your vhost config

like image 26
Eugen Rieck Avatar answered Oct 02 '22 13:10

Eugen Rieck


You can get around cross-domain security restrictions in chrome by starting it with the --disable-web-security flag.

E.g. (on OS X):

open /Applications/Google\ Chrome.app/ --args --disable-web-security
like image 23
Gareth Avatar answered Oct 01 '22 13:10

Gareth