![](/img/trans.png)
[英]Yii2 cors filters error that No 'Access-Control-Allow-Origin' header is present
[英]yii2: how 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;
}
}
你可以使用这个简单的代码:
header('Access-Control-Allow-Origin: *');
它可以添加到您的控制器action
之一或 Controller 或其他用例的beforeAction()
中(根据您的应用程序的逻辑/架构自行决定)。
https://www.yiiframework.com/doc/api/2.0/yii-base-controller#beforeAction()-detail
我已经通过更新行为() 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.