yii 2.0.50需配置cors以支持跨域api调用:全局在config/web.php中通过response组件添加access-control-allow-origin等响应头,并在urlmanager中配置'options *'路由指向sitecontroller::actionoptions()处理预检请求;生产环境应限制origin并启用access-control-allow-credentials。

Yii 2.0.50项目对外提供API时,前端页面(如Vue或React单页应用)从不同域名发起AJAX请求,浏览器因同源策略拦截响应,控制台报错“CORS header ‘Access-Control-Allow-Origin’ missing”,必须在服务端显式配置CORS响应头才能放行。
全局启用CORS中间件
打开 config/web.php,在 components 数组内添加 response 组件配置:
→ 在 'components' => [ 下新增以下键值对:
'response' => [ 'class' => 'yii\web\Response', 'on beforeSend' => function ($event) { $response = $event->sender; $response->headers->add('Access-Control-Allow-Origin', '*'); $response->headers->add('Access-Control-Allow-Methods', 'GET, POST, PUT, DELETE, OPTIONS'); $response->headers->add('Access-Control-Allow-Headers', 'Origin, X-Requested-With, Content-Type, Accept, Authorization'); $response->headers->add('Access-Control-Expose-Headers', 'X-Pagination-Total-Count, X-Pagination-Page-Count, X-Pagination-Current-Page, X-Pagination-Per-Page'); },],
这一步直接注入响应头,覆盖所有控制器动作的输出。但注意:【OPTIONS预检请求不会触发action逻辑,仅靠此配置无法响应OPTIONS】——必须配合下一步路由拦截。
拦截并响应OPTIONS预检请求
Yii默认不处理OPTIONS方法,浏览器发出的预检请求会直接返回405或404。需在URL规则中显式捕获:
→ 打开 config/web.php → 找到 urlManager 配置块 → 在 'rules' => [ 内最顶部插入:
'' => 'site/index', // 兜底规则,不可删'<strong>OPTIONS *</strong>' => 'site/options', // 关键:匹配任意路径的OPTIONS请求
→ 创建 controllers/SiteController.php,在类中添加:
public function actionOptions(){ return null; // 空响应体,仅返回204状态码和CORS头}
这一步让所有OPTIONS请求落到 SiteController::actionOptions(),由框架自动附加CORS头并返回204。不写这一行,前端发POST前的OPTIONS会被拒绝,后续请求根本发不出去。
按模块/控制器精细化控制CORS
若生产环境要求限制允许来源(如只允许 https://admin.example.com),不能用 *,需动态判断 Origin:
方法一:修改 response 组件中的 on beforeSend 回调
将原 $response->headers->add('Access-Control-Allow-Origin', '*'); 替换为:
$origin = Yii::$app->request->getHeaders()->get('Origin');$allowedOrigins = ['https://admin.example.com', 'https://shop.example.com'];if (in_array($origin, $allowedOrigins)) { $response->headers->add('Access-Control-Allow-Origin', $origin); $response->headers->add('Access-Control-Allow-Credentials', 'true'); // 若前端设 withCredentials=true,此行必加}
方法二:使用行为(Behavior)在特定控制器中启用
→ 在控制器类(如 controllers/ApiController.php)顶部添加:
use yii\filters\Cors;use yii\helpers\ArrayHelper;
→ 在 public function behaviors() 中返回:
return ArrayHelper::merge(parent::behaviors(), [ 'corsFilter' => [ 'class' => Cors::className(), 'cors' => [ 'Origin' => ['https://admin.example.com'], 'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'DELETE', 'OPTIONS'], 'Access-Control-Request-Headers' => ['*'], 'Access-Control-Allow-Credentials' => true, ], ],]);
行为方式更安全,避免全局污染;但需确保该控制器继承自 yii\rest\Controller 或手动启用 ContentNegotiator,否则JSON响应可能出错。
验证CORS是否生效
第一步:启动服务,用 curl 检查响应头
curl -H "Origin: https://admin.example.com" -I http://localhost:8080/api/v1/users
第二步:观察返回中是否含 Access-Control-Allow-Origin: https://admin.example.com 和 Access-Control-Allow-Methods 等字段
第三步:在浏览器开发者工具 Network 标签页中,点开任意一个API请求 → 查看 Response Headers → 确认 CORS 头存在且值正确
第四步:若前端仍报错,检查是否漏配 Access-Control-Allow-Credentials ——只要前端 AJAX 设置了 withCredentials: true,后端就必须返回该头且值为 true,同时 Access-Control-Allow-Origin 不能为 *。
大量免费API接口:立即使用
涵盖生活服务API、金融科技API、企业工商API、等相关的API接口服务。免费API接口可安全、合规地连接上下游,为数据API应用能力赋能!











