Issue when trying to handle CORS

Hi all,

I’m trying to perfom an ajax call on my slim API.
So I add the following middleware (adapted from something found in a former topic):

$app->add(function ($req, $res, $next) {
    $newResponse = $res->withHeader('Access-Control-Allow-Origin', '*')
                         ->withHeader('Access-Control-Allow-Headers', '*')
                         ->withHeader('Access-Control-Allow-Methods', '*');
 if ($req->isOptions()) {
     return $newResponse;
 }
return $next($req, $newResponse);
});

But with this, I am only able to perform GET requests.
For example,
I can call this method :

$app->get('/test_get', function (Request $request, Response $response) {
    $response->getBody()->write("OK");
    return $response;  
});

but I don’t manage to call this one :

$app->post('/test', function (Request $request, Response $response) {
    $response->getBody()->write("OK");
    return $response;  
});

Indeed, I get the following error : XMLHttpRequest cannot load http://localhost:8888/test. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:9000' is therefore not allowed access.

Do I miss something ?
Thanks

In here: http://www.slimframework.com/docs/cookbook/enable-cors.html

Only return with the response. Try it! :smile:

I did not notice the options route !
I Spend so much time on this … :slight_smile:

Anyway, thanks a lot!