0

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');
 });
dlopezgonzalez
  • 4,217
  • 5
  • 31
  • 42
  • which server are the access control headers setup on?`http://MY_IP/~FOLDER/foo` or `http://192.168.0.157:8100`? I suspect it's the latter. It needs to be setup on the first. – FuzzyTree Feb 16 '16 at 18:19
  • http://192.168.0.157:8100 its the phone (phone connect by usb and running a ionic app using ionic run android). http://MY_IP/~FOLDER/foo is a internet server (shared hosting). – dlopezgonzalez Feb 17 '16 at 08:06
  • Check the response headers, what do you get when trying to access the resource that gives you that issue? – Ioannis Lalopoulos Feb 17 '16 at 12:14

0 Answers0