简体   繁体   中英

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.

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:

XMLHttpRequest cannot load https://api.kraken.com/0/public/AssetPairs . No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'localhost:4200' is therefore not allowed access.

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:

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. Angular request direct to nginx which then reroute to your third part resources.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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