Yii2跨源请求被ANGULAR2阻止

时间:2017-01-25 13:46:36

标签: rest angular yii yii2

使用angular2和yii2 restful服务但它失败了 在yii2控制器中我设置了

    public function behaviors()
{
    $behaviors = parent::behaviors();
     $behaviors['corsFilter'] = [
        'class' => \yii\filters\Cors::className(),
        'cors' => [
            // restrict access to
            'Origin' => ['http://localhost:4200'],  //this is my angular2 source
            'Access-Control-Request-Method' => ['POST', 'GET','PUT', 'OPTIONS'],
            // Allow only POST and PUT methods
            'Access-Control-Request-Headers' => ['*'],
            // Allow only headers 'X-Wsse'
            // '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'],
        ],
    ];

    $auth = $behaviors['authenticator'] = [
        'class' => HttpBearerAuth::className(),
        'only' => ['can-access','profile'],  //access controller
    ];

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

在angular2 am中将标题设置为

  get(url) {
let headers = new Headers();
let token = JSON.parse(localStorage.getItem("currentUser")).token;
if (token) {
  headers.append('Authorization', 'Bearer ' + token);
  headers.append('Content-Type', 'application/x-www-form-urlencoded');
}

let options = new RequestOptions({ headers: headers });
return this.http.get(url, {headers:headers});

}

当我检查帖子请求时收到错误

Cross-Origin Request Blocked: The Same Origin Policy disallows 
reading the remote resource at     
 http://127.0.0.1/bcl/api/rest/v1/users/profile.
  (Reason: CORS preflight channel did not succeed).

互联网搜索我发现我需要像上面那样设置cors过滤器但仍然失败

2 个答案:

答案 0 :(得分:0)

正如您的错误所述,浏览器发送了预检请求,获得了允许来源的列表(在您的情况下是' http://localhost:4200')并且分开阻止您的请求。

您的请求位于" http://127.0.0.1/bcl/api/rest/v1/users/profile"当您的允许来源设置为" http://localhost:4200"。

更改

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

'Origin' => ['http://127.0.0.1'],

答案 1 :(得分:0)

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

'Origin' => ['*'],