You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何配置Laravel CORS以允许Nuxt 3请求认证API路由?

解决Nuxt 3请求Laravel认证路由的CORS问题

核心问题

闭包路由/api/authenticate能正常响应CORS,但绑定AuthenticatedSessionController@test的同一路由触发CORS错误——本质是控制器路由的中间件执行顺序问题:请求被认证类中间件拦截时,CORS响应头还未添加,导致浏览器报错。

解决步骤

1. 优先执行CORS中间件

确保CORS中间件在所有拦截类中间件之前运行,即使请求被拦截也能返回带CORS头的响应:

  • 打开app/Http/Kernel.php
  • 将CORS中间件移到全局$middleware数组最顶部:
    protected $middleware = [
        \Illuminate\Http\Middleware\HandleCors::class, // 置顶
        \App\Http\Middleware\TrustProxies::class,
        // 其他中间件...
    ];
    
    (如果项目使用fruitcake/laravel-cors包,替换为\Fruitcake\Cors\HandleCors::class)

2. 排查控制器自带中间件

AuthenticatedSessionController默认带guest中间件,该中间件针对Web场景返回重定向,且执行顺序在CORS之前,会导致API请求触发CORS错误:

  • 方案一:在路由定义时临时禁用该中间件
    // routes/api.php
    Route::post('/authenticate', [AuthenticatedSessionController::class, 'test'])->withoutMiddleware('guest');
    
  • 方案二:修改控制器中间件逻辑,适配API场景
    // app/Http/Controllers/Auth/AuthenticatedSessionController.php
    public function __construct()
    {
        // 仅针对Web路由启用guest中间件,API路由跳过
        $this->middleware('guest')->only(['create'])->except('destroy');
    }
    

3. 确保CORS配置生效

  • 清除Laravel配置和路由缓存:
    php artisan config:clear
    php artisan route:clear
    
  • 确认config/cors.php配置:
    'paths' => ['api/*', 'sanctum/csrf-cookie'],
    'allowed_origins' => ['*'], // 或明确指定http://localhost:3000
    'allowed_methods' => ['*'],
    

4. 带凭证请求的额外配置(可选)

如果需要在请求中携带Cookie等凭证:

  • Nuxt端$fetch添加credentials参数:
    $fetch('http://127.0.0.1:8000/api/authenticate', {
        method: 'POST',
        body: form,
        credentials: 'include'
    }).then(res => console.log(res))
    
  • Laravel端修改config/cors.php:
    'supports_credentials' => true,
    'allowed_origins' => ['http://localhost:3000'], // 此处不能用*,必须指定具体域名
    

验证

重启Laravel和Nuxt服务,重新发送请求,确认CORS错误消失,请求正常到达控制器方法。

内容的提问来源于stack exchange,提问作者Artur Müller Romanov

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 08:01:22