-
Notifications
You must be signed in to change notification settings - Fork 16
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Provide an example for dynamically specifying allowed methods for Slim 4 #54
Comments
I am not sure if I have ever used that feature with Slim 4. Most API projects I have are still Slim 3. I try to find if I have example somewhere. I just remember there has never been easy way to get that info. |
I have the same problem, some idea? |
same 👍🏻 |
It works for me with the following config: // init container
// ...
// init middleware
$app->options('/{routes:.+}', fn ($request, $response, $args) => $response);
$app->add(new CorsMiddleware([
'logger' => $container->getLogger(),
'origin' => array_merge(['http://localhost'], Settings::get('api.custom_safe_hosts')),
'methods' => function (ServerRequest $request): array {
$routeContext = RouteContext::fromRequest($request);
$routingResults = $routeContext->getRoutingResults();
return $routingResults->getAllowedMethods();
},
'headers.allow' => ['Authorization', 'If-Match', 'If-Unmodified-Since'],
'headers.expose' => ['Authorization', 'Etag'],
'credentials' => true,
'cache' => 60,
'error' => function (ServerRequest $request, \Slim\Psr7\Response $response, array $arguments) {
$arguments['origin'] = $_SERVER['HTTP_ORIGIN'];
return $response
->withHeader('Content-Type', 'application/json')
->withBody((new StreamFactory())->createStream(json_encode($arguments, \JSON_UNESCAPED_SLASHES | \JSON_PRETTY_PRINT)));
},
]));
// init rest of middleware, including routing middleware
$app->run(); So apparently the OPTIONS catch-all block is really needed, as stated on https://www.slimframework.com/docs/v4/cookbook/enable-cors.html |
I've trouble dynamically specifying the allowed methods while using Slim4 like you did in the readme file for Slim3
I've tried the following for Slim 4:
But either when I put
$app->addRoutingMiddleware();
in front of the code block above I get the following error:or when I put
$app->addRoutingMiddleware();
after the code block, the Cors middleware doesn't get invoked.I can mitigate the first error where it complains about the
RouteContext
when I implement aOPTIONS
catch-all block like so:But I wonder if I can get rid of the OPTIONS catch-all block altogether, what I'm missing here?
The text was updated successfully, but these errors were encountered: