Skip to content
Advertisement

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 = 'apimodulesv1modelsDoctor';

    public function behaviors()
    {

        $behaviors = parent::behaviors();



        $behaviors['access'] = [
            'class' => yiifiltersAccessControl::className(),
            'rules' => [
                [
                    // All actions
                    'allow' => true,
                    'actions' => ['index', 'view'],
                ],
            ],
        ];

        return $behaviors;
    }
}

Please Help!

Advertisement

Answer

I have solved it by updating the behaviors() function

    public function behaviors()
    {

        $behaviors = parent::behaviors();

        $behaviors['corsFilter'] = [
            'class' => yiifiltersCors::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' => yiifiltersAccessControl::className(),
            'rules' => [
                [
                    // All actions
                    'allow' => true,
                    'actions' => ['index', 'view'], // add more
                ],
            ],
        ];

        return $behaviors;
    }
User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement