SLIM PUT-Request CORS Header missing

454 views Asked by At

I've tried to set up a Angular App with SLIM Framework v4 Backend; Angular is running local, while Slim is on a Deploy Server. So CORS Setup is needed and I did like given in the documentation:

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

$app->add(function ($request, $handler) {
    $response = $handler->handle($request);
    return $response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
        ->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, PATCH, OPTIONS');
});

On get Requests the Acces-Control-Allow-Origin Header is present; no problem, everything working as expected. On Put request (example):

$app->put('/event/{id}', function (Request $request, Response $response, $args) use ($app) {
$id = $args['id'];
$response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization');
$response->getBody()->write('Test with $id');
return $response;
});

even with an additional add in the function, the header is not present on the response in the browser.

What am I doing wrong?

1

There are 1 answers

0
odan On

The request and response object is immutable. You can try this:

$app->put('/event/{id}', function (Request $request, Response $response, $args) {
    $id = $args['id'];

    $response = $response
        ->withHeader('Access-Control-Allow-Origin', '*')
        ->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization');

    $response->getBody()->write('Test with $id');

    return $response;
}