I am working on a project where I need to fetch data from the Delhi Metro Rail API, which has CORS enabled. However, I am getting a "Not Authorized" response when I make a fetch request from an HTML file, even though the request is successful when made from Node.js using the same code. Here is the code I am using:
let apiEndpoint = "https://backend.delhimetrorail.com/api/v2/en/station_route/UDB/NFGH/least-distance/2023-06-04T12:14:46.695";
let proxyUrl = "[my-proxy-url]"; // Hidden for security
let finalUrl = proxyUrl + apiEndpoint;
fetch(finalUrl, {
headers: {
Referer: "https://www.delhimetrorail.com/",
Origin: "https://www.delhimetrorail.com",
},
})
.then((response) => response.json())
.then((data) => console.log(data))
.catch((e) => console.log(e));
I've set up a proxy server using cors-anywhere (no changes made) and hosted it on Heroku. When I run this code through Node.js, I get the correct response. But when I run the same code from an HTML file (hosted on GitHub pages or locally in firefox using the Live Server VS Code extension), I get a 200 OK status but the response data is "Not Authorized".
I also tried to compare the request headers when making requests from Node.js and from the HTML file, but I'm unable to understand the differences and why it would result in different responses.
An additional challenge I encountered is the lack of documentation for the Delhi Metro Rail API. I discovered this API endpoint through network analysis of the Delhi Metro Rail website, and noticed that while most of the API endpoints appeared to be open, the 'station_route' endpoint seemed to require the same origin. This is the endpoint I am interested in for my application, and I am trying to understand how I can access it effectively and consistently, despite these hurdles. I cannot contact them to add my domain or anything but now that I have seen that I get a response by running node server.js I think it might be possible to get that data for my front end.
Could someone explain why this is happening, and how to fix it? I need to fetch this data from a client-side HTML file.
Thank you!