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:
The real problem is that if we set -Allow-
for all request (OPTIONS
& POST
), Chrome will cancel it.
The following code works for me with POST
to LocalHost with Chrome
<?php
if (isset($_SERVER['HTTP_ORIGIN'])) {
//header("Access-Control-Allow-Origin: {$_SERVER['HTTP_ORIGIN']}");
header("Access-Control-Allow-Origin: *");
header('Access-Control-Allow-Credentials: true');
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
}
if ($_SERVER['REQUEST_METHOD'] == 'OPTIONS') {
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_METHOD']))
header("Access-Control-Allow-Methods: GET, POST, OPTIONS");
if (isset($_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']))
header("Access-Control-Allow-Headers:{$_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']}");
exit(0);
}
?>
Chrome will make requests with CORS from a localhost
origin just fine. This isn't a problem with Chrome.
The reason you can't load http://stackoverflow.com
is that the Access-Control-Allow-Origin
headers weren't allowing your localhost
origin.
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 lvh.me
(which points at 127.0.0.1 just like localhost) or start chrome with the --disable-web-security
flag (assuming you're just testing).