Reputation: 404
I've created a custom middleware in Laravel for my project. It adds the following headers:
return $next($request)
->header('Access-Control-Allow-Origin', '*')
->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS')
->header('Access-Control-Allow-Headers',' Origin, Content-Type, Accept, Authorization, X-Request-With')
->header('Access-Control-Allow-Credentials',' true');
The middleware seems to work fine for Postman. When I trigger a POST request via Postman, you'll notice the headers have been added to the response:
However, for Chrome this doesn't seem to work. See the headers which have been returned from Google Chrome (same request, using axios for the calls):
This results in the following error in the console of Google Chrome:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/auth/jwt/token' from origin 'http://localhost:3000' 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.
What am I doing wrong/is causing this odd issue?
Upvotes: 0
Views: 1688
Reputation: 134
i know that this post is a little old, now Laravel comes with an integrated cors solution at the config/cors.php file, but what keeps giving headaches regarding this, is that there is a line that says "paths"
'paths' => ['api/*', 'sanctum/csrf-cookie'];
This is the main problem, leave this value just like this:
'paths' => ['*'];
Or insert an array for every route in your API and your cors problem is gone! Just to clarify, Cors is not a firewall, and postman does not send preflight or some other extra informations that chrome do.
Upvotes: 2
Reputation: 1234
Just put similar script on the very top of your file, with a die().
<?php
if (isset($_SERVER["REQUEST_METHOD"])) {
if ($_SERVER["REQUEST_METHOD"] === "OPTIONS") {
header("Access-Control-Allow-Origin: *");
header("Access-Control-Allow-Methods: GET, POST, PUT, PATCH, DELETE");
// header("Access-Control-Allow-Headers: X-Protection-Token");
die();
}
}
If you could translate into laravel, better. Implementation example is at here.
Upvotes: 3
Reputation: 574
Instead of creating custom Laravel middleware, I'd highly recommend using the Laravel CORS Package. No need to reinvent the wheel.
Upvotes: 3