![](/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.