I am creating a simple API with CakePHP 4, and I am having some issues with some CORS
requests.
Access to XMLHttpRequest at 'http://localhost/myapp.api/elaborations/add.json' from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.
Everything works with every other request and after some digging I've found that the error was an undefined index in my controller. If I fix that, the CORS
error disappears. I just didn't see it in my log files, it's my bad.
It's a bit confusing seeing a CORS
error because of a coding error though. I guess the issue could be in my CORS
configuration, and hence this question.
This is what I've ended with, after a little bit of web search, trials and errors. I know it's ugly but I couldn't find anything better that actually worked.
How can I avoid having CORS
errors for coding issues? I guess there is some redirect action somewhere, but I can't figure out how to avoid it.
<?php
namespace AppMiddleware;
use PsrHttpMessageResponseInterface;
use PsrHttpMessageServerRequestInterface;
use PsrHttpServerRequestHandlerInterface;
use PsrHttpServerMiddlewareInterface;
class CorsMiddleware implements MiddlewareInterface
{
public function process(
ServerRequestInterface $request,
RequestHandlerInterface $handler
): ResponseInterface
{
// Calling $handler->handle() delegates control to the *next* middleware
// In your application's queue.
$response = $handler->handle($request);
if ($request->getHeader('Origin')) {
$allowedDomains = [
'https://myapp.it',
'https://www.myapp.it',
'http://localhost:3000',
];
$origin = $_SERVER['HTTP_ORIGIN'];
if (in_array($origin, $allowedDomains)) {
header('Access-Control-Allow-Origin: ' . $origin);
}
header('Access-Control-Allow-Methods: POST, GET, PUT, PATCH, DELETE, OPTIONS');
header('Access-Control-Allow-Headers: *');
if (strtoupper($request->getMethod()) === 'OPTIONS') {
exit(0);
}
}
return $response;
}
}
question from:https://stackoverflow.com/questions/65951557/cors-errors-because-of-internal-app-error