我正在尝试使用angular2 cli访问此URL,但却出现访问控制错误
http://safety.trucksafetyinspection.co.ke/rest/v1/new/profile?access-token=my-token
我添加了proxy.config.json
个文件
{
"/rest/v1/*":{
"target":"http://safety.trucksafetyinspection.co.ke",
"secure":false,
"logLevel":"debug"
}
}
但仍然出现
的错误No Access-Control-Allow-Origin' header is present on the requested resource. Origin
在package.config.json
中"scripts": {
"ng": "ng",
"start": "ng serve --proxy-config proxy.config.json",
},
所以在ng build
或npm start
或甚至ng serve
之后仍然会出现此错误。可能有什么不对?
更新:后端位于yii2,ive设置cors过滤器为
public function behaviors()
{
return [
'corsFilter' => [
'class' => \yii\filters\Cors::className(),
'cors' => [
// restrict access to
'Origin' => ['*'],
'Access-Control-Request-Method' => ['POST', 'PUT','OPTIONS','GET'],
// Allow only POST and PUT methods
'Access-Control-Request-Headers' => ['X-Wsse'],
// 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'],
],
],
];
}
答案 0 :(得分:0)
这听起来不像是我的代理错误。这听起来像是一个交叉起源(CORS)问题。当src域与某些浏览器请求的dest域不同时会发生这种情况。
e.g。 src域名是woogle.com但是dest域名是noogle.com
您有两种选择,要么让您的网络服务器重写请求
OR
将Access-Control标头添加到后端服务器。这些标头(如果存在)定义哪些OTHER域可以向您的服务器发出请求。
例如......
Access-Control-Allow-Origin: http://foo.example
Access-Control-Allow-Methods: POST, GET, OPTIONS
Access-Control-Allow-Headers: X-PINGOTHER, Content-Type
Access-Control-Max-Age: 86400
如何在服务器上设置这些标头取决于它的Node Express,Apache,NGINX等
有关详细信息,请参阅https://developer.mozilla.org/en-US/docs/Web/HTTP/Access_control_CORS