我已經開發了Angular & Yii2 REST服務。在跨域有問題。 下面添加我的角度& Yii2 REST代碼。Yii2 REST +角度跨域域CORS
AngularJs:(像 'http://organization1.example.com', 'http://organization2.example.com',....)
$http.defaults.useXDomain = true;
$http.defaults.withCredentials = true;
$http.defaults.headers.common['Authorization'] = 'Bearer ' + MYTOKEN
我的要求,從角控制器:
apiURL = 'http://api.example.com';
$http.get(apiURL + '/roles')
.success(function (roles) { })
.error(function() { });
Yii2的.htaccess:(REST URL像「 http://api.example.com「)
Header always set Access-Control-Allow-Origin: "*"
Header always set Access-Control-Allow-Credentials: true
Header always set Access-Control-Allow-Methods "POST, GET, PUT, DELETE, OPTIONS"
Header always set Access-Control-Allow-Headers "Authorization,X-Requested-With, content-type"
Yii2我的行爲:
public function behaviors() {
$behaviors = parent::behaviors();
$behaviors['corsFilter'] = [
'class' => Cors::className(),
'cors' => [
'Origin' => ['*'],
'Access-Control-Expose-Headers' => [
'X-Pagination-Per-Page',
'X-Pagination-Total-Count',
'X-Pagination-Current-Page',
'X-Pagination-Page-Count',
],
],
];
$behaviors['authenticator'] = [
'class' => HttpBearerAuth::className(),
'except' => ['options'],
];
$behaviors['contentNegotiator'] = [
'class' => ContentNegotiator::className(),
'formats' => [
'application/json' => Response::FORMAT_JSON,
],
];
return $behaviors;
}
問題
從我的角度請求是 'GET' 的方法,但它會進入 '選項' 方法&返回401未經授權錯誤(CORS)。因爲請求授權標頭不發送。
現在這是記錄在這裏明確:http://www.yiiframework.com/doc-2.0/guide-rest-controllers。html#cors - 只要按照這個指南,它會工作。總結:確保CORS行爲之後進行身份驗證,並始終從身份驗證中排除OPTIONS。 – jlapoutre
已更新。謝謝@jlapoutre –