I'm using the Peloton API to generate statistics based on workout data grabbed from their API. Certain API requests require the user to be logged in, which can be done by sending your username and password to /auth/login. It returns a session ID that is needed to get those locked requests, such as workout history. The session ID is seemingly sent as a cookie (using credentials: 'include').
When I set credentials to include, it says "Access to fetch at (url) from origin (my site) has been blocked by CORS policy: The value of the 'Access-Control-Allow-Origin' header in the response must not be the wildcard '\*' when the request's credentials mode is 'include'. How do I fix this? My code is below.
async function loginAndGetData(username, password) {
const info = { 'username_or_email': username, 'password': password };
const response = await fetch("https://pelotoncors.herokuapp.com/https://api.onepeloton.com/auth/login",
{
method: 'POST',
body: JSON.stringify(info)
});
const loginInfo = await response.json();
const workoutInfo = await fetch('https://pelotoncors.herokuapp.com/https://api.onepeloton.com/api/user/' + loginInfo.user_id + '/workouts?limit=1234567890',
{
method: 'GET',
credentials: 'include'
});
}
So I identified multiple problems:
Logically, to prevent the use of the API by anybody, Paleton, like anybody else who builds a serious API, decided to put CORS headers on their responses, which is obviously not only from a security standpoint reasonable, but can be quite annoying because it makes it basically impossible to use the API from the browsers because the browser enforces the CORS-headers that are being set on responses by the servers.
So your first idea with cors-anywhere seems rational, but doesn't work because you use credentials: 'include' which requires the 'Access-Control-Allow-Origin' header to NOT be set to wildcard *.
If you are not familiar of what all that above means, let me run you through it:
In your above code, which I assume because of the above error message you run on a browser, you try to make a fetch call to cors-anywhere with the URL of the API and userId. Cors-anywhere makes the call to the API for you and ignores the CORS-Headers (it can do that because it is just a policy created for browsers to increase security), send you the data it gets from the API back BUT with the 'Access-Control-Allow-Origin' (by default) set to wildcard *. Because you use credentials: 'include' though, which requires the 'Access-Control-Allow-Origin' header do NOT be set on wildcard, your browser detects a CORS-policy violation, and you get the above error.
So what can you do now ?
I guess the problem is your backend on Heroku, you need to set header "Access-Control-Allow-Origin": true on your backend.