yii2: 如何设置 Access-Control-Allow-Origin header
yii2: how to set Access-Control-Allow-Origin header
我有这个 yii2 控制器,我想在其中设置 Access-Control-Allow-Origin: *
header
class DoctorController extends ActiveController
{
public $modelClass = 'api\modules\v1\models\Doctor';
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['access'] = [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
// All actions
'allow' => true,
'actions' => ['index', 'view'],
],
],
];
return $behaviors;
}
}
请帮忙!
您可以使用这个简单的代码:
header('Access-Control-Allow-Origin: *');
它可能会被添加到您的控制器 action
或控制器的 beforeAction()
或其他用例中(根据您的应用程序 logic/architecture 自行决定)。
https://www.yiiframework.com/doc/api/2.0/yii-base-controller#beforeAction()-detail
我已经通过更新 behaviors() 函数解决了
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET'], // add more
'Access-Control-Request-Headers' => ['*'],
'Access-Control-Allow-Credentials' => null,
'Access-Control-Max-Age' => 86400,
],
];
$behaviors['access'] = [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
// All actions
'allow' => true,
'actions' => ['index', 'view'], // add more
],
],
];
return $behaviors;
}
我有这个 yii2 控制器,我想在其中设置 Access-Control-Allow-Origin: *
header
class DoctorController extends ActiveController
{
public $modelClass = 'api\modules\v1\models\Doctor';
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['access'] = [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
// All actions
'allow' => true,
'actions' => ['index', 'view'],
],
],
];
return $behaviors;
}
}
请帮忙!
您可以使用这个简单的代码:
header('Access-Control-Allow-Origin: *');
它可能会被添加到您的控制器 action
或控制器的 beforeAction()
或其他用例中(根据您的应用程序 logic/architecture 自行决定)。
https://www.yiiframework.com/doc/api/2.0/yii-base-controller#beforeAction()-detail
我已经通过更新 behaviors() 函数解决了
public function behaviors()
{
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => \yii\filters\Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Request-Method' => ['GET'], // add more
'Access-Control-Request-Headers' => ['*'],
'Access-Control-Allow-Credentials' => null,
'Access-Control-Max-Age' => 86400,
],
];
$behaviors['access'] = [
'class' => \yii\filters\AccessControl::className(),
'rules' => [
[
// All actions
'allow' => true,
'actions' => ['index', 'view'], // add more
],
],
];
return $behaviors;
}