[英]yii2: how to set Access-Control-Allow-Origin header
I have this yii2 controller where I want to set Access-Control-Allow-Origin: *
header我有这个 yii2 controller 我想设置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;
}
}
You may use this simple code:你可以使用这个简单的代码:
header('Access-Control-Allow-Origin: *');
It may be added into one of your controller's action
or into beforeAction()
of your Controller or other use case (at your discretion according to the logic/architecture of your application).它可以添加到您的控制器action
之一或 Controller 或其他用例的beforeAction()
中(根据您的应用程序的逻辑/架构自行决定)。
https://www.yiiframework.com/doc/api/2.0/yii-base-controller#beforeAction()-detail https://www.yiiframework.com/doc/api/2.0/yii-base-controller#beforeAction()-detail
I have solved it by updating the behaviors() function我已经通过更新行为() function 解决了这个问题
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;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.