Why does my http://localhost CORS origin not work?
I am stuck with this CORS problem, even though I set the server (nginx/node.js) with the appropriate headers.
I can see in Chrome Network pane -> Response Headers:
Access-Control-Allow-Origin:http://localhost
which should do the trick.
Here's the code that I now use to test:
var xhr = new XMLHttpRequest();
xhr.onload = function() {
console.log('xhr loaded');
};
xhr.open('GET', 'http://stackoverflow.com/');
xhr.send();
I get
XMLHttpRequest cannot load http://stackoverflow.com/. Origin http://localhost is not allowed by Access-Control-Allow-Origin.
I suspect it's a problem in the client script and not server configuration...
Solution 1:
Chrome does not support localhost for CORS requests (a bug opened in 2010, marked WontFix in 2014).
To get around this you can use a domain like localho.st
(which points at 127.0.0.1 just like localhost) or start chrome with the --disable-web-security
flag (assuming you're just testing).
Solution 2:
Per @Beau's answer, Chrome does not support localhost CORS requests, and there is unlikely any change in this direction.
I use the Allow-Control-Allow-Origin: * Chrome Extension to go around this issue. The extension will add the necessary HTTP Headers for CORS:
Access-Control-Allow-Origin: *
Access-Control-Allow-Methods: "GET, PUT, POST, DELETE, HEAD, OPTIONS"
Access-Control-Expose-Headers: <you can add values here>
The source code is published on Github.
Note that the extension filter all URLs by default. This may break some websites (for example: Dropbox). I have changed it to filter only localhost URLs with the following URL filter
*://localhost:*/*
Solution 3:
None of the extensions worked for me, so I installed a simple local proxy. In my case https://www.npmjs.com/package/local-cors-proxy It is a 2-minute setup:
(from their site)
npm install -g local-cors-proxy
API endpoint that we want to request that has CORS issues:
https://www.yourdomain.ie/movies/list
Start Proxy:
lcp --proxyUrl https://www.yourdomain.ie
Then in your client code, new API endpoint:
http://localhost:8010/proxy/movies/list
Worked like a charm for me: your app calls the proxy, who calls the server. Zero CORS problems.