CORS header ‘Access-Control-Allow-Origin’ missing Yii2

I have set up my rest controller following this guide Yii Rest Guide here is my CORS configurations

$behaviors = parent::behaviors();

        // remove authentication filter

        $auth = $behaviors['authenticator'] = [

            'class' => HttpBasicAuth::className(),

        ];

        unset($behaviors['authenticator']);

   

        $behaviors['corsFilter'] = [

            'class' => \yii\filters\Cors::className(),

            'cors' => [

                'Origin' => [ 'http://localhost:8100' ],

                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],

                'Access-Control-Request-Headers' => ['*'],

                'Access-Control-Allow-Credentials' => true,

                'Access-Control-Max-Age' => 86400,

            ],

        ];  

            // re-add authentication filter

        $behaviors['authenticator'] = $auth;

        // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)

        $behaviors['authenticator']['except'] = ['options'];

        return $behaviors;

When I make a POST Request here is what I get on the Browser

**

The Same Origin Policy disallows reading the remote resource at http://localhost:8101/profiles/create. (Reason: CORS header ‘Access-Control-Allow-Origin’ missing).

**

Here is my ProfileController

<?php

namespace api\controllers;

use Yii;

//use api\models\ProfilesQuery;

use yii\rest\ActiveController;

use yii\web\NotFoundHttpException;

use yii\filters\auth\HttpBasicAuth;

/**

 * ProfilesController implements the CRUD actions for Profiles model.

 */

class ProfilesController extends ActiveController

{

    public $modelClass = 'api\models\Profiles'; 

    public function behaviors()

    {

        $behaviors = parent::behaviors();

        // remove authentication filter

        $auth = $behaviors['authenticator'] = [

            'class' => HttpBasicAuth::className(),

        ];

        unset($behaviors['authenticator']);

   

        $behaviors['corsFilter'] = [

            'class' => \yii\filters\Cors::className(),

            'cors' => [

                'Origin' => [ 'http://localhost:8100' ],

                'Access-Control-Request-Method' => ['GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS'],

                'Access-Control-Request-Headers' => ['*'],

                'Access-Control-Allow-Credentials' => true,

                'Access-Control-Max-Age' => 86400,

            ],

        ];  

            // re-add authentication filter

        $behaviors['authenticator'] = $auth;

        // avoid authentication on CORS-pre-flight requests (HTTP OPTIONS method)

        $behaviors['authenticator']['except'] = ['options'];

 

        return $behaviors;

    }

      /**

     * Creates a new Profiles model.

     * If creation is successful, the browser will be redirected to the 'view' page.

     * @return mixed

     */

    public function actionCreate()

    {

        $model = new Profiles();

        if ($model->load(Yii::$app->request->post()) && $model->save()) {

            return $model;

            //return $this->redirect(['view', 'id' => $model->ProfileID]);

        }

        return 'Failed!';

    }

     /**

     * Finds the Profiles model based on its primary key value.

     * If the model is not found, a 404 HTTP exception will be thrown.

     * @param integer $id

     * @return Profiles the loaded model

     * @throws NotFoundHttpException if the model cannot be found

     */

    protected function findModel($id)

    {

        if (($model = Profiles::findOne($id)) !== null) {

            return $model;

        }

        throw new NotFoundHttpException('The requested page does not exist.');

    }

  
      

}

What Might I be Doing Wrong?

After spending the whole day debugging this Handling of CORS in ionic question Stackoverflow helped me solve it.

1 Like