Search code examples
phpyii2yii2-advanced-app

yii2: how to set Access-Control-Allow-Origin header


I have this yii2 controller where I want to set 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;
    }
}

Please Help!


Solution

  • I have solved it by updating the behaviors() 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;
        }