I have got a tiny server with Slim Framework (index.php):
$app = new \Slim\Slim();
$corsOptions = array(
"origin" => "*",
"exposeHeaders" => array("Content-Type", "X-Requested-With", "X-authentication", "X-client"),
"allowMethods" => array('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS')
);
$cors = new \CorsSlim\CorsSlim($corsOptions);
$app->add($cors);
$app->post('/foo', function () use ($app) {
...
echo "foo";
});
When I tried to attack the post method from my app (phone app) using Ionic (phonegap app) I obtain this message:
XMLHttpRequest cannot load http://MY_IP/~FOLDER/foo. Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://192.168.0.157:8100' is therefore not allowed access. The response had HTTP status code 404.
Code:
$http.post(rest_service_url + '/foo', {
data: ...
}).then(
function(res){
console.log("OK");
},
function(err){
console.log("ERROR", err);
}
);
I tested these solutions found over Internet but no one works:
Use CorsSlim:
$corsOptions = array(
"origin" => "*",
"exposeHeaders" => array("Content-Type", "X-Requested-With", "X-authentication", "X-client"),
"allowMethods" => array('GET', 'POST', 'PUT', 'DELETE', 'OPTIONS')
);
$cors = new \CorsSlim\CorsSlim($corsOptions);
Put this in .htaccess
Header set Access-Control-Allow-Origin "*"
Header set Access-Control-Allow-Methods: "GET,POST,OPTIONS,DELETE,PUT"
Put this on top of index.php
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Headers: Content-Type');
header('Access-Control-Allow-Methods: GET, PUT, POST, DELETE, OPTIONS');
Use this after Slim creation:
$app->options('/(:name+)', function() use($app) {
$response = $app->response();
$app->response()->status(200);
$response->header('Access-Control-Allow-Origin', '*');
$response->header('Access-Control-Allow-Headers', 'Content-Type, X-Requested-With, X-authentication, X-client');
$response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});