我正在开发一个 Laravel 应用程序,该应用程序需要处理来自 Vue 3 前端的请求的 CORS。我遇到与凭据相关的 CORS 错误,我需要帮助在 Laravel 后端中正确配置 CORS。
尝试从 Vue 应用程序向 Laravel 后端发出 XMLHttpRequest 时收到以下错误:
Access to XMLHttpRequest at 'http://127.0.0.1:8000/api/oauth/token' from origin 'http://127.0.0.1:5173' has been blocked by CORS policy: Response to preflight request doesn't pass access control check: The value of the 'Access-Control-Allow-Credentials' header in the response is '' which must be 'true' when the request's credentials mode is 'include'.
您可以通过在中间件中手动设置适当的标头来处理 Laravel 中的 CORS。具体方法如下:
创建一个自定义中间件来处理 CORS 设置:
php artisan make:middleware HandleCors
打开新创建的
HandleCors.php
文件并修改它以包含必要的 CORS 标头:
namespace App\Http\Middleware;
use Closure;
class HandleCors
{
/**
* Handle an incoming request.
*
* @param \Illuminate\Http\Request $request
* @param \Closure $next
* @return mixed
*/
public function handle($request, Closure $next)
{
$response = $next($request);
$response->headers->set('Access-Control-Allow-Origin', 'http://127.0.0.1:5173'); // or other domain
$response->headers->set('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
$response->headers->set('Access-Control-Allow-Headers', 'Content-Type, Authorization');
$response->headers->set('Access-Control-Allow-Credentials', 'true');
// Handle preflight requests
if ($request->getMethod() === 'OPTIONS') {
$response->setStatusCode(200);
return $response;
}
return $response;
}
}
在
app/Http/Kernel.php
文件中注册中间件。您可以将其添加到全局中间件堆栈或仅添加到 api
中间件组:
protected $middleware = [
// ...
\App\Http\Middleware\HandleCors::class,
// ...
];
// OR in the $middlewareGroups for 'api'
protected $middlewareGroups = [
'api' => [
// ...
\App\Http\Middleware\HandleCors::class,
],
];
如果遇到任何问题,请清除配置缓存:
php artisan config:cache