1

问题现象

当通过ajax访问yii2的rest-api时,提示错误

NO 'Access-Control_Allow-Origin' header is present on the requested resource.

解决方法

编辑rest-api的controller,在behaviors中增加cors

use yii\filters\Cors;
use yii\helpers\ArrayHelper;
public function behaviors()
{
  return ArrayHelper::merge(parent::behaviors(), [
    'authenticator' => [
       'class' => QueryParamAuth::className(),
     ],   
     [
       'class' => Cors::className(),
       'cors' => [
       'Origin' => ['http://123.123.com','http://234.234.com'],//定义允许来源的数组
       'Access-Control-Request-Method' => ['GET','POST','PUT','DELETE', 'HEAD', 'OPTIONS'],//允许动作的数组
                ],
       'actions' => [
         'index' => [
           'Access-Control-Allow-Credentials' => true,
          ]
        ]
      ],
    ]);
  }

cors 属性

cors['Origin']: 定义允许来源的数组,可为['*'] (任何用户) 或 ['http://www.myserver.net', 'http://www.myotherserver.com']. 默认为 ['*'].
cors['Access-Control-Request-Method']: 允许动作数组如 ['GET', 'OPTIONS', 'HEAD']. 默认为 ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'].
cors['Access-Control-Request-Headers']: 允许请求头部数组,可为 ['*'] 所有类型头部 或 ['X-Request-With'] 指定类型头部. 默认为 ['*'].
cors['Access-Control-Allow-Credentials']: 定义当前请求是否使用证书,可为 true, false 或 null (不设置). 默认为 null.
cors['Access-Control-Max-Age']: 定义请求的有效时间,默认为 86400.

给指定动作设置CORS头部

可以覆盖默认参数为每个动作调整CORS 头部。例如,为login动作增加Access-Control-Allow-Credentials参数如下所示:

public function behaviors()
{
    return ArrayHelper::merge([
        [
            'class' => Cors::className(),
            'cors' => [
                'Origin' => ['http://www.myserver.net'],
                'Access-Control-Request-Method' => ['GET', 'HEAD', 'OPTIONS'],
            ],
            'actions' => [
                'login' => [
                    'Access-Control-Allow-Credentials' => true,
                ]
            ]
        ],
    ], parent::behaviors());
}

参考文章:http://www.yiichina.com/doc/g...


zebrayoung
240 声望35 粉丝