Hi,
I have an API written in PHP (7.4.0) following the very nice and useful tutorial.
Everything works really well as long as I use Postman for my requests. I have to say that I am still struggling to force Slim to emit errors in JSON format. I absolutely do not need HTML as Slim is used only as a RESTful API… I find it really difficult to make this possible as it should be a simple feature. But that is not my question here.
I have built a web application that is trying to authenticate the users on the API which sends a JWT token back when the authentication is successful. Again, that works like a breeze in Postman… But as soon as I try with a browser (Chrome in my case) I struggle with CORS issues… I did setup the tuupola/cors-middleware package and I read an followed most of the tutorial I could find but nothing seems to work.
I am convinced that there is something wrong in my code which is very much dependent on the code found in the tutorial by @odan (Absolutely nothing wrong with the tutorial but rather with my understanding of it)
So, here is the question: How to get rid of that CORS issue?
Access to XMLHttpRequest at 'http://localhost:8000/v2/atzn/login' from origin 'http://localhost:4200' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource.
My routes.php (only part of it here) looks like:
<?php
use Slim\App;
return function (App $app) {
$app->get('/', \App\Action\HomeAction::class);
$app->group('/v2', function ($app) {
// Authentication
$app->group('/atzn', function ($app) {
$app->post('/login', \App\Action\Authentication\LoginAction::class);
$app->post('/register', \App\Action\Authentication\RegisterAction::class);
});
I have a cors.php used as a middleware looking like:
<?php
use Slim\App;
use Tuupola\Middleware\CorsMiddleware;
use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;
return function (App $app) {
$logger = new Logger("CORS");
$rotating = new RotatingFileHandler(__DIR__ . "/../logs/slim.log", 0, Logger::DEBUG);
$logger->pushHandler($rotating);
$app->add(new Tuupola\Middleware\CorsMiddleware([
"logger" => $logger,
"origin" => ["*"],
"methods" => ["GET", "POST", "PUT", "PATCH", "DELETE"],
"headers.allow" => ["Authorization", "If-Match", "If-Unmodified-Since"],
"headers.expose" => [],
"credentials" => true,
"cache" => 0
]));
};
Could someone help me?
Thanks a million in advance.
Pierre