我有以下问题:在我的Angular 4应用程序中,我想从公共API获取(GET请求)数据 .
只是从浏览器或Postman调用URL工作得很好但是当我从Angular发出HTTP Get请求时我得到了这个错误:
XMLHttpRequest无法加载https://api.kraken.com/0/public/AssetPairs . 请求的资源上不存在“Access-Control-Allow-Origin”标头 . 因此不允许原点'localhost:4200'访问 .
我找到了解决方案,但没有一个解决了我的问题,因为它是第三方API而不在我的控制之下......我也尝试设置 Headers ,但它不起作用:
let headers = new Headers({ 'Access-Control-Allow-Origin': 'true' , 'Content-Type':'application/json', 'crossDomain':'true'});
let options = new RequestOptions({ headers: headers, withCredentials: false});
return this.http.get('https://api.kraken.com/0/public/AssetPairs' , options)
.map(
(response: Response) => {
console.log(response);
const markets = response.json();
return markets;
},
(error: Error) => {
console.log('error');
console.log(error);
}
);
提前感谢您的建议!
1 回答
我建议你使用代理服务器 . 您可以通过代理服务器访问第三方资源 . 例如,你在nginx.conf中添加了nginx服务器并添加了cors配置 . Angular请求直接指向nginx,然后重新路由到您的第三方资源 .