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

Laravel+Vue.js跨域请求问题求助:CORS头缺失致请求被拦截

解决Laravel + Vue.js的跨域(CORS)问题

Hey there, sorry to hear you’ve been stuck on this CORS issue for two days—trust me, this is one of the most common roadblocks when pairing Laravel and Vue, and it’s totally fixable!

The problem here is straightforward: your browser’s Same Origin Policy blocks the request because Laravel isn’t sending the required Access-Control-Allow-Origin header. Postman works fine because it doesn’t enforce this policy like web browsers do. Let’s walk through the easiest and most reliable solutions:

方法1:使用官方推荐的barryvdh/laravel-cors包(最简便)

This is the standard approach for Laravel projects, as it handles all edge cases (like preflight OPTIONS requests) out of the box:

  • Install the package via Composer:
    composer require barryvdh/laravel-cors
    
  • Register the middleware: Open app/Http/Kernel.php, and add \Barryvdh\Cors\HandleCors::class to either:
    • The $middleware array (applies CORS to all routes, good for development)
    • The $middlewareGroups['api'] array (only applies to your API routes, better for production)
  • Publish the configuration file:
    php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider"
    
  • Configure allowed origins: Open config/cors.php and adjust these settings:
    'paths' => ['api/*'], // 确保匹配你的API路由规则
    'allowed_origins' => ['*'], // 开发环境用*;生产环境替换为你的前端域名(比如'http://localhost:8080')
    'allowed_methods' => ['*'],
    'allowed_headers' => ['*'],
    

方法2:手动添加CORS响应头(无需额外包)

如果你不想安装第三方包,可以自定义一个中间件:

  • 生成新的中间件:
    php artisan make:middleware Cors
    
  • 打开app/Http/Middleware/Cors.php,更新handle方法:
    public function handle(Request $request, Closure $next)
    {
        $response = $next($request);
    
        // 开发环境允许所有来源;生产环境替换为你的前端域名
        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS');
        $response->header('Access-Control-Allow-Headers', 'Content-Type, Authorization');
    
        return $response;
    }
    
  • 注册中间件:像之前提到的,把\App\Http\Middleware\Cors::class添加到app/Http/Kernel.php的$middleware或$middlewareGroups['api']数组中。

额外注意事项

  • 重启服务器:修改配置后,重启Laravel开发服务器和Vue开发服务器——有时候缓存会导致配置不生效。
  • Vue/Axios配置:检查你的Axios baseURL是否正确指向Laravel API(比如http://localhost/lsapp/public/api)。
  • 生产环境安全:生产环境绝对不要用'*'作为allowed_origins,一定要指定精确的前端域名,避免安全风险。

内容的提问来源于stack exchange,提问作者Julie Robert

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.27 09:17:46