简体   繁体   中英

OPTIONS request before GET request with Authorization Header not working in slim framework 4

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.

I just added options all route, where I wanted use:

Example If I use it in /api/user route, then I add this code:

$app->options('/api/user', function ($request, $response, $args) {
    return $response;
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM