Imran Omar Bukhsh
Imran Omar Bukhsh

Reputation: 8071

CORS issue with PHP (Yii2) AngularJS

Keep getting the cors issue. Have already tried the following:

  1. adding code you can see in the image in yii2
  2. have installed the Cors Plugin in firefox

API URL : http://thisisbig.ae/advanced/backend/web/customersapi/update/?id=2

enter image description here

Upvotes: 0

Views: 349

Answers (2)

Azraar Azward
Azraar Azward

Reputation: 1624

Use a behavior to define this

public function behaviors()
{
    return [
        'verbs' => [
            'class' => \yii\filters\VerbFilter::className(),
            'actions' => [
                'index'  => ['GET'],
                'view'   => ['GET'],
                'create' => ['GET', 'POST'],
                'update' => ['GET', 'PUT', 'POST'],
                'delete' => ['POST', 'DELETE'],
            ],
        ],
    ];
} 

You can also use CORS filter by attaching it as a behavior to a controller or module, like the following,

public function behaviors()
{
    return [
        'corsFilter' => [
            'class' => \yii\filters\Cors::className(),
        ],
    ];
}

you can also use CORS filter to restrict parameters, like this,

public function behaviors()
{
    return [
        'corsFilter' => [
            'class' => \yii\filters\Cors::className(),
            'cors' => [
                // restrict access to
                'Origin' => ['http://www.myserver.com', 'https://www.myserver.com'],
                // Allow only POST and PUT methods
                'Access-Control-Request-Method' => ['POST', 'PUT'],
                // Allow only headers 'X-Wsse'
                'Access-Control-Request-Headers' => ['X-Wsse'],
                // Allow credentials (cookies, authorization headers, etc.) to be exposed to the browser
                'Access-Control-Allow-Credentials' => true,
                // Allow OPTIONS caching
                'Access-Control-Max-Age' => 3600,
                // Allow the X-Pagination-Current-Page header to be exposed to the browser.
                'Access-Control-Expose-Headers' => ['X-Pagination-Current-Page'],
            ],

        ],
    ];
}

Upvotes: 2

Imran Omar Bukhsh
Imran Omar Bukhsh

Reputation: 8071

In the back-end ( Yii2 ), needed to override the verbs() function in the controller and add 'OPTIONS' for the 'update' value

protected function verbs()
{
    return [
        'index' => ['GET', 'HEAD'],
        'view' => ['GET', 'HEAD'],
        'create' => ['POST'],
        'update' => ['PUT', 'PATCH','OPTIONS'],
        'delete' => ['DELETE'],
    ];
} 

Upvotes: 2

Related Questions