Laravel 10+Vue3跨域登录报错:CORS缺失Allow Origin如何解决?
解决Laravel 10 + Vue.js 3分离应用的CORS跨域问题
1. 确保CORS中间件在API路由组中启用
打开app/Http/Kernel.php,找到$middlewareGroups中的api数组,确认包含\Illuminate\Http\Middleware\HandleCors::class:
protected $middlewareGroups = [ 'web' => [ // ... 其他已存在的中间件 ], 'api' => [ \Illuminate\Http\Middleware\HandleCors::class, // 必须存在这一行 \Laravel\Sanctum\Http\Middleware\EnsureFrontendRequestsAreStateful::class, \Illuminate\Routing\Middleware\ThrottleRequests::class.':api', \Illuminate\Routing\Middleware\SubstituteBindings::class, ], ];
2. 配置CORS允许的来源与请求规则
打开config/cors.php,根据你的前端环境修改核心配置项:
return [ 'paths' => ['api/*'], // 匹配所有API路由 'allowed_methods' => ['POST', 'OPTIONS', 'GET'], // 按需允许请求方法,生产环境避免用* 'allowed_origins' => ['http://localhost:5173'], // 替换为你的Vue应用实际域名/端口(比如Vite默认5173) 'allowed_headers' => ['Content-Type', 'Authorization'], // 明确允许的请求头,生产环境避免用* 'supports_credentials' => true, // 若需携带Cookie(如Sanctum认证),设为true 'max_age' => 3600, // 预检请求缓存时长,减少重复OPTIONS请求 ];
注意:生产环境禁止用
*作为allowed_origins,必须指定具体前端域名,降低安全风险。
3. 刷新配置缓存(可选但推荐)
如果之前执行过配置缓存命令,需清除缓存让新配置生效:
php artisan config:clear
4. 前端请求优化(可选)
把硬编码的API地址换成环境变量,避免地址拼写错误:
在Vue项目的.env文件中添加:
VITE_API_URL=http://localhost/api
修改请求代码:
const handleLogin = () => { axios.post(`${import.meta.env.VITE_API_URL}/login`, getFormattedCredentials()) .then((response) => { console.log(response.data) waitingOnVerification.value = true }) .catch((error) => { console.error(error) alert(error.response?.data?.message || '登录失败') }) }
若开启了
supports_credentials,需在axios全局配置中开启携带Cookie:axios.defaults.withCredentials = true
常见问题排查
- 若仍报404:确认Laravel服务运行端口(默认8000),前端请求地址需对应
http://localhost:8000/api/login,避免端口混淆。 - 预检请求失败:检查
allowed_methods是否包含OPTIONS,CORS中间件会自动处理OPTIONS请求,无需手动添加路由。
内容的提问来源于stack exchange,提问作者Narakaya
相关产品推荐
相关产品推荐

