Hello,
I’ve used the following snippet suggested in the User Guide to enable CORS headers on all responses:
$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response;
});
$app->add(function ($req, $res, $next) {
$response = $next($req, $res);
return $response
->withHeader('Access-Control-Allow-Origin', 'http://localhost')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
});
This works fine when sending GET requests from my frontend (in AngularJS) but as soon as I try a POST request, I get the following error in the browser console:
XMLHttpRequest cannot load http://localhost:8888/accounts. No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost' is therefore not allowed access.
When checking in the Network tab of the browser dev console, I see that CORS headers are sent along the response to the OPTIONS request but not for the response of the POST request that follows.
I even tried to add the headers directly on the response of the actual route but no luck:
$app->post('/account/new', function (Request $request, Response $response) {
$data = $request->getParsedBody();
$account_data = [];
$account_data['name'] = filter_var($data['name'], FILTER_SANITIZE_STRING);
$account_data['market_id'] = filter_var($data['market_id'], FILTER_SANITIZE_NUMBER_INT);
$account_data['category_id'] = filter_var($data['category_id'], FILTER_SANITIZE_NUMBER_INT);
$account_data['flag'] = 'TEST_RESPONSE';
$response->withJson($account_data);
return $response
->withHeader('Access-Control-Allow-Origin', 'http://localhost')
->withHeader('Access-Control-Allow-Headers', 'X-Requested-With, Content-Type, Accept, Origin, Authorization')
->withHeader('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
});
I’m sure I’m missing something silly, thanks for any help!