I have cloned slim skeleton (https://github.com/slimphp/Slim-Skeleton) which already have CORS implemented. But still when API calls OPTIONS before GET, it sends 405 ERROR "Method not allowed. Must be one of: GET"
Here is my route where I face this error. $group->get('/users', ListUsersAction::class);
$app->group('', function (Group $group) {
$group->post('/user/create', CreateUsersAction::class);
$group->get('/users', ListUsersAction::class);
$group->get('/user/{id}', ViewUserAction::class);
})->add(AuthenticationMiddleware::class);
The same route is working from postman. And same route is working if I remove Authorization token from header.
Execution does not even reach to first line of "AuthenticationMiddleware".
However I tested it by adding same option route without "AuthenticationMiddleware".
like this:
$app->options('/users', function(Request $request, Response $response) {return $response;});
$app->group('', function (Group $group) {
$group->post('/user/create', CreateUsersAction::class);
$group->get('/users', ListUsersAction::class);
$group->get('/user/{id}', ViewUserAction::class);
})->add(AuthenticationMiddleware::class);
This is working. So I guess I forgot to add some code or I did any miskate which causing the error, or the skeleton has a bug.
Can anyone help on this? Thanks in advance.
Okay I found the solution.
You can use a wildcard OPTIONS
request to avoid this issue / error.
Below is an example:
$app->options('/{routes:.+}', function ($request, $response, $args) {
return $response;
});
I have tested it and currently working fine for me.
In my test, as mentioned, I tried it by creating OPTIONS
route for /users
, it was working but creating OPTINOS
route for all API route get created is doesn't make sense, here is the solution as wildcard OPTIONS
route.
thanks @odan for taking time to comment, but wildcard OPTIONS
route is better solution.