CORS issues trying to perform oauth

API Discussion
I cannot for the life of me solve this issue.
I have a react app (A), an express api proxy (B), and then battlenet api (C).

In the react app, I need the user to login so I can make battlenet api calls... so I setup a proxy so I don't have to expose the client id/secrets in the front-end.

A: localhost:3000
B: localhost:3001
C: battlenet


I have a `"proxy": "http://localhost/3001"` setup in my `package.json`. So i can do things like `fetch('/api/foo')` in site A, and it'll hit site B successfully.

In site B, I am using `passport` and `passport-bnet` to handle the oauth. If I start up site B, and hit the oauth endpoint, it will successfully go out to site C and auth itself and bring back the token I need.

_BUT_ if I do something like this in site A:

function Foo(() => {
return <button onClick={handleOnClick}>Click Me</button>

function handleOnClick() {
// doesn't work
fetch('/api/auth').then(...)
}
});


Then I will receive a cors error.
Access to fetch at 'https://us.battle.net/oauth/authorize?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A3001%2Fauth%2Fbnet%2Fcallback&scope=wow.profile&client_id=.............' (redirected from 'http://localhost:3001/auth/bnet') 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.


If I change my <button onClick={...}> to an anchor tag, then it works:

// works
return <a href="/api/auth">Click Me</a>
fetch() says "hey JavaScript, load this URL behind the scenes and give me the result" which requires CORS.

But that /oauth/authorize page is intended to be shown to the user in the browser window, not loaded behind the scenes.

Don't use fetch(), instead set location.href='/api/auth' or whatever so it loads in the browser. If they're already logged in and your app is already authorized, you'll bounce across a few redirects and land back at your redirect_uri with the code.
Thanks that worked!

Join the Conversation

Return to Forum