So I have setup CORS in my Slim 3 application. I’m using Angular6 for frontend. Cors is working fine, but then I saw a strange behaviour when doing a DELETE.
So according to https://www.slimframework.com/docs/v3/cookbook/enable-cors.html when you have grouped your routes (wich I have) and want to do a DELETE method, you should map it with OPTIONS. So basicly thats works, but now I’ve noticed that my code is executed twice (one in the PREFLIGHT OPTIONS and then with the DELETE method.
So what I do is trying to delete a record from the database, but first I look it up with Eloquent in my model:
$currentPage = Page::find($id);
if(!$currentPage) return false;
$currentPage->delete();
return true;
Then in my controller I return true or false in a json. So what I’ve noticed that my borwser console log I see 2 request (as suspected) : OPTION and DELETE. The OPTION doesn’t have any response, the DELETE has a json response with “false”. And when I lookup the record in de database, it’s gone. So it seems that the OPTION request already deleted the row, so the DELETE request can’t find it.
My Cors middleware:
public function __invoke(Request $request, Response $response, $next)
{
$router = $this->getContainer()->router;
$route = $request->getAttribute("route");
$methods = [];
if (!empty($route)) {
$pattern = $route->getPattern();
foreach ($router->getRoutes() as $route) {
if ($pattern === $route->getPattern()) {
$methods = array_merge_recursive($methods, $route->getMethods());
}
}
//Methods holds all of the HTTP Verbs that a particular route handles.
} else {
$methods[] = $request->getMethod();
}
$response = $next($request, $response);
return $response
->withHeader("Access-Control-Allow-Methods", implode(",", $methods))
->withHeader("Access-Control-Allow-Origin" , "*")
->withHeader("Access-Control-Allow-Headers" , "cache-control, Origin, Content-Type, Accept, Authorization, X-Request-With")
->withHeader("Access-Control-Allow-Credentials" , "true")
;
}
And my route:
$this->map(['DELETE', 'OPTIONS'] , '/{id}/delete', '\Controllers\Cms\Page:deletePage');
How do I prevent the OPTION code execution?