Deadly CORS when http://localhost is the 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).
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:*/*
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);
}
?>