Laravel 6需手动配置fruitcake/laravel-cors并启用supports_credentials,同时allowed_origins必须明确列出前端域名(不可用*),中间件须通过bootstrap/app.php的append方式注册,且前端fetch需设置credentials: 'include'。

Laravel 6 默认不支持带凭证的跨域请求(如 Cookie、Authorization Header),要开启 credentials 支持,必须同时满足配置、中间件、前端三端协同,缺一不可。
配置 supports_credentials 并约束 allowed_origins
在 config/cors.php 中,关键设置如下:
-
'supports_credentials' => true—— 启用凭证支持 -
'allowed_origins' => ['http://localhost:3000']—— *不能写 `['']**,必须明确列出前端域名(开发可用https://www.php.cn/link/9bd290791415c81d9aa6cd5997724774https://app.example.com) -
'paths' => ['api/*', 'sanctum/csrf-cookie']—— 确保包含 API 路由和 CSRF 接口路径,否则预检失败 -
'allowed_headers' => ['*']或显式列出['Content-Type', 'Authorization', 'X-Requested-With'] -
'exposed_headers' => ['XSRF-TOKEN'](若用 Sanctum,建议加上)
⚠️ 注意:
allowed_origins写['*']+supports_credentials => true会导致浏览器直接拒绝请求,并报错:
“The value of the 'Access-Control-Allow-Origin' header must not be the wildcard '' when the request's credentials mode is 'include'”*
正确注册 CORS 中间件
Laravel 6 不自动启用该中间件,需手动追加到 bootstrap/app.php 的 withMiddleware 回调中:
$middleware->append(\Fruitcake\Cors\HandleCors::class);
✅ 确保不是只加在 web 组或局部路由里;它必须对 api/* 请求生效。
❌ 不要加在全局 $middleware 数组顶部——应放在 EncryptCookies 之后、认证中间件之前,避免被提前拦截。
前端 fetch 必须显式声明 credentials
React/Vue 等前端发起请求时,必须设置:
fetch('/api/user', {
credentials: 'include', // 关键!不能省略
headers: { 'Content-Type': 'application/json' }
})若用 Axios:
axios.defaults.withCredentials = true;
验证是否生效的实操方式
别只看浏览器 Network 面板的状态码,要检查响应头:
curl -X OPTIONS http://your-app.test/api/user \ -H "Origin: http://localhost:3000" \ -H "Access-Control-Request-Method: GET" \ -I
成功响应应含:
-
Access-Control-Allow-Origin: http://localhost:3000 -
Access-Control-Allow-Credentials: true -
Access-Control-Allow-Methods: GET, POST, ... Access-Control-Allow-Headers: Content-Type, Authorization, ...
若返回 404 或缺失这些头,说明中间件未触发——优先排查 paths 是否匹配、中间件注册位置、以及路由是否存在(尤其 OPTIONS 方法本身无需定义路由,但中间件必须覆盖到该路径)。


















