Laravel 5 API与Ionic 1(Angular 1)CORS跨域问题求助
我之前也遇到过一模一样的问题!直接在index.php里加CORS头没用,核心原因是浏览器的预检OPTIONS请求没被Laravel正确处理——浏览器在发送POST/PUT等非简单请求前,会先发送OPTIONS请求验证权限,而这个请求往往没走到你加的index.php代码那里,就返回了没有CORS头的响应。
给你两个靠谱的解决方案:
方案一:自定义CORS中间件(手动控制)
这是最灵活的方式,完全自己掌控逻辑:
- 先生成一个新的中间件:
php artisan make:middleware Cors - 打开生成的
app/Http/Middleware/Cors.php,替换成下面的代码:<?php namespace App\Http\Middleware; use Closure; class Cors { public function handle($request, Closure $next) { // 生产环境建议替换成你的前端实际域名,不要用* $allowedOrigin = 'http://localhost:8100'; // 处理实际请求的响应头 $response = $next($request); $response->header('Access-Control-Allow-Origin', $allowedOrigin); $response->header('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); $response->header('Access-Control-Allow-Headers', 'Content-Type, Authorization, X-Requested-With'); // 专门处理OPTIONS预检请求,直接返回200和头 if ($request->isMethod('OPTIONS')) { return response('', 200)->withHeaders([ 'Access-Control-Allow-Origin' => $allowedOrigin, 'Access-Control-Allow-Methods' => 'GET, POST, PUT, DELETE, OPTIONS', 'Access-Control-Allow-Headers' => 'Content-Type, Authorization, X-Requested-With', ]); } return $response; } } - 注册中间件:打开
app/Http/Kernel.php,把这个中间件加到全局中间件数组里(这样所有路由都生效):protected $middleware = [ // ...其他已有的中间件 \App\Http\Middleware\Cors::class, ];
方案二:用成熟的Laravel CORS包(更省心)
如果不想自己写中间件,可以用社区维护的包,比如barryvdh/laravel-cors:
- 安装包:
composer require barryvdh/laravel-cors - 发布配置文件(Laravel 5.5+会自动注册服务提供者,不用手动加):
php artisan vendor:publish --provider="Barryvdh\Cors\ServiceProvider" - 打开
config/cors.php,配置你的前端域名和允许的方法:return [ 'paths' => ['api/*'], // 只给API路由加CORS,按需调整 'allowed_methods' => ['*'], 'allowed_origins' => ['http://localhost:8100'], // 你的前端地址 'allowed_origins_patterns' => [], 'allowed_headers' => ['*'], 'exposed_headers' => [], 'max_age' => 0, 'supports_credentials' => false, ]; - 最后把中间件加到API路由组里:打开
app/Http/Kernel.php,在$middlewareGroups的api数组里添加:'api' => [ // ...其他中间件 \Barryvdh\Cors\HandleCors::class, ];
为什么直接加index.php没用?
简单说,OPTIONS预检请求是浏览器自动发的,当Laravel找不到对应OPTIONS请求的路由时,会直接返回404,这时候你在index.php里加的头根本没机会被执行。只有让Laravel明确处理OPTIONS请求,返回带CORS头的响应,浏览器才会允许后续的实际请求。
试一下上面的方案,应该就能解决你的问题了!
内容的提问来源于stack exchange,提问作者Sam Prasanna
相关产品推荐
相关产品推荐

