根据
docs
你应该先取消设置
authenticator
筛选以添加
Cors
过滤,所以你的行为应该看起来像
public function behaviors() {
$behaviors = parent::behaviors();
$auth=$behaviors['authenticator'];
// remove authentication filter necessary because we need to
// add CORS filter and it should be added after the CORS
unset($behaviors['authenticator']);
// add CORS filter
$behaviors['corsFilter'] = [
'class' => '\yii\filters\Cors',
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],
'Access-Control-Request-Headers' => ['*'],
],
];
// re-add authentication filter
$behaviors['authenticator'] = $auth;
// avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)
$behaviors['authenticator']['except'] = ['options'];
return $behaviors;
}
通过添加
beforeAction
像下面
public function beforeAction($action)
{
Yii::$app->response->format = Response::FORMAT_JSON;
return true;
}