简体   繁体   English

解决Angular中的CORS问题(无法访问API)?

[英]Resolving CORS issue in Angular (without access to API)?

I have the following problem: In my Angular 4 App I want to get (GET Request) data from a public API. 我有以下问题:在我的Angular 4应用程序中,我想从公共API获取(获取请求)数据。

Just calling the URL from Browser or via Postman works perfectly but when I make an HTTP Get request from Angular I get that error: 仅从浏览器或通过Postman调用URL即可正常工作,但是当我从Angular发出HTTP Get请求时,出现该错误:

XMLHttpRequest cannot load https://api.kraken.com/0/public/AssetPairs . XMLHttpRequest无法加载https://api.kraken.com/0/public/AssetPairs No 'Access-Control-Allow-Origin' header is present on the requested resource. 所请求的资源上没有“ Access-Control-Allow-Origin”标头。 Origin 'localhost:4200' is therefore not allowed access. 因此,不允许访问源“ localhost:4200”。

I found solutions for that but none of them resolved my issue as it is a third party API and not under my control... I also tried setting headers but it didn't work: 我找到了解决方案,但没有一个解决了我的问题,因为它是第三方API,不受我的控制...我也尝试设置标头,但没有用:

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);
        }
      );

Thanks in advance for advice! 预先感谢您的建议!

I suggest you to use proxy-server. 我建议您使用代理服务器。 You can access your third part resources though proxy server. 您可以通过代理服务器访问第三方资源。 For instance you put nginx server and add cors configuration in the nginx.conf. 例如,您放置了nginx服务器,并在nginx.conf中添加了cors配置。 Angular request direct to nginx which then reroute to your third part resources. Angular请求直接发送到nginx,然后将其重新路由到您的第三方资源。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM