-2

There's a public API that gives a response when directly hit from the browser. I am using Chrome browser. Below is the API - https://query1.finance.yahoo.com/v7/finance/chart/abc?range=7d&interval=1m

When I hit the same API from angular, it gives me below error -

Access to XMLHttpRequest at 'https://query1.finance.yahoo.com/v7/finance/chart/?range=7d&interval=1m' from origin 'http://localhost:4200' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

Below is my code -

this._http.get(url).subscribe(
      (resp) => {
          console.log(resp);
      },
      (error) => {
        console.log(error);
      }
);

There's a solution proposed to use the following command - chrome.exe --user-data-dir="C:/Chrome dev session" --disable-web-security. It works, but I want a solution that works with a normal browser. Because once I host this, general users obviously won't use that command.

harshit
  • 17
  • 2

1 Answers1

0

By default, untrusted sites are not allowed to make requests to other sites. CORS allows a mechanism for the target website to make exemptions for that (but for obvious reasons not the requesting website), but since you presumably don't control Yahoo's web servers you can't do that. As such, there is no way for you to directly access the Yahoo API from your Angular client application.

What you can do, however, is access it from a server, and then forward the data on to your Angular client app. For development and insignificant production purposes, you can also use a third-party CORS proxy for this. thingproxy provides such a free proxy server, and it will forward the response of any API URL appended to https://thingproxy.freeboard.io/fetch/.

You can, for example, use code similar to this:

function getCorsProxiedUrl(url: string): string
{
    return `https://thingproxy.freeboard.io/fetch/${url}`;
}
this._http.get(getCorsProxiedUrl(url)).subscribe(
    (resp) => {
        console.log(resp);
    },
    (error) => {
        console.log(error);
    }
);
Sara E
  • 179
  • 1
  • 3
  • Thanks, this worked. But is it really a good idea to keep the dependency on a proxy server? It may not exist in the future or change, in that case, we will have to move to another proxy server. This solution will work for my case, but is there any workaround for this if we want to implement it in a significant product environment? – harshit May 23 '21 at 17:10
  • The thingproxy proxy server is open source so, you can host it on-premises, or you can develop your own proxy server. Other than that, there is no other way around this without controlling Yahoo's servers. – Sara E May 23 '21 at 17:16