Search code examples
phpcorsslimsame-origin-policyslim-3

PHP Slim - No Access-Control-Allow-Origin header is present on the requested resource


I'm new to Slim framework. I'm building a REST API and I'm having problems implementing CORS.

First I went along with the example from the Slim cookbook:

Then I used /tuupola/cors-middleware :

I came up with this:

$app->options('/{routes:.+}', function ($request, $response, $args) {
    return $response;
});

$app->add(new Tuupola\Middleware\CorsMiddleware([
    "origin" => ["*"],
    "methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"],
    "headers.allow" => [],
    "headers.expose" => [],
    "credentials" => false,
    "cache" => 0,
]));

The problem is with routes that have a placeholder argument. For example:

$app->get('/items', 'ItemsController:index');
$app->get('/items/{id}', 'ItemsController:getItem');

The response from /items has a 'Access-Control-Allow-Origin: *' header, but the one from /items/{id} does not and this results in errors (CORS policy). How can I solve this issue?


Solution

  • I caused the problem myself, it's not a Slim issue. I created a temporary error handler method with this code:

    $json = array("error" => [
        "message" => $message,
        "code"    => $code
    ]);
    
    exit(json_encode($json));
    

    Simply setting a header solves the issue:

    header('Access-Control-Allow-Origin: *');