cors配置不生效主因是未启用或错放handlecors中间件,且allowed_origins与supports_credentials组合不当;需检查nginx/apache是否放行options请求,并确保前端withcredentials、后端session cookie属性及反向代理设置协同一致。

为什么 cors.php 配置不生效?
最常见的原因是没启用 Laravel 自带的 CORS 中间件,或者中间件没注册到正确位置。Laravel 7+ 默认自带 fruitcake/laravel-cors 包(新版已整合进核心),但它的中间件不会自动加载到全局中间件栈里。
- 检查
app/Http/Kernel.php的$middlewareGroups['api']是否包含\Fruitcake\Cors\HandleCors::class(Laravel 8+ 是\Illuminate\Http\Middleware\HandleCors::class) - 如果只在 API 路由用跨域,别加到
$middleware全局数组——否则所有请求(含登录页、静态资源)都会带上 CORS 头,可能干扰调试 - 运行
php artisan config:clear后再试,cors.php配置受缓存影响明显
config/cors.php 里哪些配置最关键?
多数问题出在 allowed_origins 和 supports_credentials 的组合逻辑上。浏览器对带 cookie 的请求(比如登录态)要求极其严格,稍有不匹配就直接拦截预检(OPTIONS)请求。
-
'allowed_origins' => ['https://your-app.com']:不能写*,除非明确不需要携带凭证;若开发时用http://localhost:3000,必须完整写入 -
'supports_credentials' => true:一旦开启,allowed_origins就不允许是*,否则浏览器直接报错The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '*' when the request's credentials mode is 'include' -
'allowed_headers' => ['*']在生产环境慎用,某些网关或 CDN 会拒绝通配;建议显式列出:['Content-Type', 'X-Requested-With', 'Authorization']
前端发请求还是被拦,但后端日志没看到 OPTIONS 请求?
说明预检(OPTIONS)请求根本没到达 Laravel,大概率卡在 Nginx / Apache 或负载均衡层。Laravel 只处理成功路由到它的请求,而预检是浏览器自动发的、不带 body 的轻量请求,容易被 Web 服务器丢弃。
- Nginx 配置里必须显式放行 OPTIONS 方法:
if ($request_method = 'OPTIONS') { add_header Access-Control-Allow-Origin "*"; add_header Access-Control-Allow-Methods "GET,POST,OPTIONS,PUT,DELETE"; add_header Access-Control-Allow-Headers "DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization"; add_header Access-Control-Max-Age 1728000; add_header Content-Length 0; add_header Content-Type text/plain; return 204; } - Cloudflare 或阿里云 SLB 等中间件默认过滤 OPTIONS,需在控制台开启“CORS 支持”或自定义响应头
- 用
curl -v -X OPTIONS http://your-api.com/api/foo直接测接口,确认是否真有响应,而不是只看浏览器 Network 面板
用了 Sanctum / Passport 后跨域登录失败?
这是典型的身份验证链路断裂:跨域请求带 withCredentials: true,但 Session Cookie 没被浏览器发送,或者后端没正确设置 Cookie 属性。
- 前端 Axios 实例必须设
withCredentials: true;Fetch 必须加credentials: 'include' - Laravel 的
config/session.php中:'domain' => '.your-app.com'(注意开头的点),且'secure' => true仅限 HTTPS 环境,开发时设为false - 确保响应头中出现
Set-Cookie,且SameSite=None; Secure组合只在 HTTPS 下合法;HTTP 开发环境请用SameSite=Lax或临时关闭 SameSite 校验(不推荐长期)











