PHP(Yii2)AngularJS的CORS问题

时间:2018-08-29 09:44:54

标签: php angularjs yii2 cors

请继续获取cors问题。 已经尝试了以下方法:

  1. 添加您可以在yii2图片中看到的代码
  2. 已在Firefox中安装了Cors插件

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

enter image description here

2 个答案:

答案 0 :(得分:2)

在后端(Yii2)中,需要覆盖控制器中的verbs()函数并为“ update”值添加“ OPTIONS”

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

答案 1 :(得分:2)

使用行为进行定义

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'],
            ],
        ],
    ];
} 

您还可以通过将CORS过滤器作为行为附加到控制器或模块来使用它,如下所示,

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

您还可以使用CORS过滤器来限制参数,例如

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'],
            ],

        ],
    ];
}