簡體   English   中英

解決Angular中的CORS問題(無法訪問API)?

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

我有以下問題:在我的Angular 4應用程序中,我想從公共API獲取(獲取請求)數據。

僅從瀏覽器或通過Postman調用URL即可正常工作,但是當我從Angular發出HTTP Get請求時,出現該錯誤:

XMLHttpRequest無法加載https://api.kraken.com/0/public/AssetPairs 所請求的資源上沒有“ Access-Control-Allow-Origin”標頭。 因此,不允許訪問源“ localhost:4200”。

我找到了解決方案,但沒有一個解決了我的問題,因為它是第三方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);
        }
      );

預先感謝您的建議!

我建議您使用代理服務器。 您可以通過代理服務器訪問第三方資源。 例如,您放置了nginx服務器,並在nginx.conf中添加了cors配置。 Angular請求直接發送到nginx,然后將其重新路由到您的第三方資源。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM