最推荐使用 fruitcake/laravel-cors 包(Laravel 9+ 已内置),通过配置 Cors 中间件并正确设置 allowed_origins 与 supports_credentials,确保 API 路由启用且响应头生效。

在 Laravel 中处理 CORS 跨域请求,最推荐的方式是使用官方维护的 fruitcake/laravel-cors 包(Laravel 9+ 已内置支持,无需额外安装),通过配置中间件统一控制响应头。
启用并配置 CORS 中间件
Laravel 默认已注册 Cors 中间件(位于 app/http/Kernel.php 的 $middleware 或 $middlewareGroups 中)。确保 API 路由组(如 api)已应用该中间件:
// app/Http/Kernel.php protected $middlewareGroups = [ 'api' => [ LaravelSanctumHttpMiddlewareEnsureFrontendRequestsAreStateful::class, 'throttle:api', IlluminateRoutingMiddlewareSubstituteBindings::class, FruitcakeCorsHandleCors::class, // ✅ 确保这一行存在 ], ];
发布并修改 CORS 配置文件
运行命令生成配置文件(Laravel 9+ 可跳过,但建议仍执行以自定义):
php artisan vendor:publish --provider="FruitcakeCorsCorsServiceProvider"
然后编辑 config/cors.php,常见安全又实用的配置示例如下:
return [ 'paths' => ['api/*', 'sanctum/csrf-cookie'], 'allowed_methods' => ['*'], 'allowed_origins' => ['http://localhost:3000', 'https://your-frontend.com'], 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 3600, 'supports_credentials' => true, // 若需携带 Cookie 或 Authorization ];
- paths:指定哪些 URL 前缀启用 CORS,如
api/*表示所有 API 接口 - allowed_origins:不要写
*(与supports_credentials => true冲突),应明确列出前端域名 - supports_credentials:设为
true时,前端必须设置credentials: 'include',后端才能读取 Cookie 或发送带认证的请求
针对特定路由临时关闭或调整 CORS
如果某接口需要特殊处理(比如允许任意源调试),可在路由定义中单独指定中间件参数:
// routes/api.php Route::get('/public-data', [DataController::class, 'index']) ->middleware('cors:{"allowedOrigins":["*"],"supportsCredentials":false}');
⚠️ 注意:生产环境避免使用 "*" 作为 allowedOrigins,尤其开启凭证时会直接被浏览器拒绝。
验证响应头是否生效
发起一个跨域请求(如用 fetch 访问 http://localhost:8000/api/user),检查响应头中是否包含:
access-Control-Allow-Origin: http://localhost:3000-
Access-Control-Allow-Credentials: true(如果启用了凭证) -
Access-Control-Allow-Headers: *或具体列表
若缺失,检查中间件是否正确注册、配置是否被缓存(可运行 php artisan config:clear)。
基本上就这些。CORS 不复杂但容易忽略细节,重点就是配对 allowed_origins 和 supports_credentials,再确认中间件跑在目标路由上。