Tegrty / Sport-Link-Connect

MIT License
0 stars 0 forks source link

Strava - API authorization #26

Open vasilyl1 opened 1 year ago

vasilyl1 commented 1 year ago

GETTING INTO THE FOLLOWING ISSUE, BROWSER ERROR:

Access to fetch at 'https://www.strava.com/oauth/authorize?client_id101485&redirect_uri=localhost&response_type=&approval_prompt=auto&scope=read,activity:read' from origin 'null'

has been blocked by CORS policy:

No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

POSSIBLE RESOLUTION, located at

https://stackoverflow.com/questions/43262121/trying-to-use-fetch-and-pass-in-mode-no-cors

mode: 'no-cors' won’t magically make things work. In fact it makes things worse, because one effect it has is to tell browsers, “Block my frontend JavaScript code from seeing contents of the response body and headers under all circumstances.” Of course you never want that.

What happens with cross-origin requests from frontend JavaScript is that browsers by default block frontend code from accessing resources cross-origin. If Access-Control-Allow-Origin is in a response, then browsers relax that blocking and allow your code to access the response.

But if a site sends no Access-Control-Allow-Origin in its responses, your frontend code can’t directly access responses from that site. In particular, you can’t fix it by specifying mode: 'no-cors' (in fact that’ll ensure your frontend code can’t access the response contents).

However, one thing that will work: if you send your request through a CORS proxy.

You can also easily deploy your own proxy to Heroku in just 2-3 minutes, with 5 commands:

git clone https://github.com/Rob--W/cors-anywhere.git cd cors-anywhere/ npm install heroku create git push heroku master After running those commands, you’ll end up with your own CORS Anywhere server running at, for example, https://cryptic-headland-94862.herokuapp.com/.

Prefix your request URL with your proxy URL; for example:

https://cryptic-headland-94862.herokuapp.com/https://example.com Adding the proxy URL as a prefix causes the request to get made through your proxy, which:

Forwards the request to https://example.com. Receives the response from https://example.com. Adds the Access-Control-Allow-Origin header to the response. Passes that response, with that added header, back to the requesting frontend code. The browser then allows the frontend code to access the response, because that response with the Access-Control-Allow-Origin response header is what the browser sees.

This works even if the request is one that triggers browsers to do a CORS preflight OPTIONS request, because in that case, the proxy also sends back the Access-Control-Allow-Headers and Access-Control-Allow-Methods headers needed to make the preflight successful.