Cors policy filter not work |
I make a filter to fix CORS Policy errors:
CorsFilter.php: PHP Code: namespace App\Filters; Filters.php PHP Code: public array $aliases = [ Routes.php: PHP Code: $routes->post('api/login', 'Api\Auth\LoginController::jwtLogin', ['filter' => 'cors']); Now in action CorsFilter Doesn't work and I've faced with this error: Code: Access to XMLHttpRequest at 'http://api/auth/jwt' from origin 'http://localhost:5173' 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. Just For Test: I put my code in index.php and surprisingly, this worked truly and fix CORS policy errors. How to create a filter to fix CORS policy errors?!
You need to set OPTIONS routes.
If there is no route, control filters does not execute. Also, you should not send 'Access-Control-Allow-Origin: *'. You should set your origin URL. (03-15-2024, 03:28 AM)kenjis Wrote: You need to set OPTIONS routes. I changed routes to: Code: $routes->options('api/login', 'Api\Auth\LoginController::jwtLogin', ['filter' => 'cors']); And Changed: Code: header('Access-Control-Allow-Origin: http://localhost:5173'); Both of them return same error.
Is the route correct? You need to define all routes for OPTIONS requests.
First of all, everyone should understand what CORS is. https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS |
Welcome Guest, Not a member yet? Register Sign In |