我已经开发了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 –