RetroAchievements / api-js

The official JavaScript library for getting achievement, user, and game data from RetroAchievements.
https://api-docs.retroachievements.org
MIT License
48 stars 7 forks source link

CORS error when using from frontend #108

Open makmonty opened 1 month ago

makmonty commented 1 month ago

I get a CORS error (preflight OPTIONS request fails) when I try to use the library from a frontend app.

I created a minimal setup project here https://github.com/makmonty/ra-bug-min-rep

Note: I don't get the error if I do the same requests with my own implementation as such:

const result = await fetch('https://retroachievements.org/API/API_GetGame.php?y=<webApiKey>&z=<username>&i=<gameId>')
const data = await result.json()

So it's not a configuration issue at the API side.

My environment is:

Browser: Firefox 131.0 SO: Arch Linux

wescopeland commented 1 month ago

Hi @makmonty!

Thanks for reporting this issue. There must be something strange going on. I just created a new React app as a test, and I am indeed able to make API calls through the library with client-side JS:

Screenshot 2024-10-12 at 11 31 20 AM

Here's my very minimal source code:

import { buildAuthorization, getUserProfile } from "./index";

function App() {
  const username = "WCopeland";
  const webApiKey = "redacted";

  const authorization = buildAuthorization({ username, webApiKey });

  const handleButtonClick = async () => {
    const userProfile = await getUserProfile(authorization, {
      username: "xelnia",
    });

    console.log(userProfile);
  };

  return <button onClick={handleButtonClick}>make api call</button>;
}

export default App;

However, it's worth noting that I'm not seeing a preflight OPTIONS call in my network tab at all. A simple GET like this with no custom headers shouldn't be triggering a preflight request.

Is it possible your Vue app is injecting anything into the HTTP call? Custom headers, etc? Any sort of "interference" like this will likely trigger a preflight request.

makmonty commented 1 month ago

I tried your code and it didn't work for me. BUT, I tried to run both your code and mine on Chrome and both worked fine. As you said, on Chrome the preflight call doesn't happen, but it does on Firefox. Another thing I noted is that the preflight request doesn't happen in my own implementation of the API. It's only made when I use the @retroachievements/api package on Firefox :shrug: