0

I'm trying to implement google login in my app and I ran into a frustrating problem. I have my react app running on port 3000 and my express server is on port 5000. I'm also using passport to authenticate users. When I'm trying to login via google and I hit the route bellow I'm get the error

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

From what I read, I have to set up CORS on the express server (which I did using the cors library). Even doing so, I still get this error. Bellow is the code:

PASSPORT:

module.exports = passport => {
  passport.use(
    new GoogleStrategy(
      {
        clientID: keys.googleClient,
        clientSecret: keys.googleSecret,
        callbackURL: "/auth/google/callback"
      },
      (token, refreshToken, profile, done) => {
        return done(null, {
          profile: profile,
          token: token
        });
      }
    )
  );

ROUTE:

router.post(
  "/auth/google",
  passport.authenticate("google", {
    session: false,
    scope: ["profile"]
  }),
  (req, res) => {
    if (!req.token) {
      return res
        .status(401)
        .json("Not authorized");
    } else {
      console.log(req.token);
    }
  }
);

To enable CORS all I did was include the cors library and use it with express:

//enables cors
app.use(cors()); 

Maybe I misunderstood this entire CORS thing. How should I approach this?

Ovidiu G
  • 1,253
  • 5
  • 25
  • 47

2 Answers2

0

The browser error message provides a hint as to the correct origin to set:

No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'http://localhost:3000' is therefore not allowed access.

Per the docs:

app.use(cors({ origin: "http://localhost:3000" }))

Wil Moore III
  • 6,968
  • 3
  • 36
  • 49
0

you are making request from localhost:3000 to localhost:5000 they do not have same origin, so for security browser will not make this request. to circumvent you have to use proxy.

since you did not mention about webpack I belive you are using CRA (create-react-app). this is how you should set up proxy in CRA.

In the client side directory:

npm i http-proxy-middleware --save

Create setupProxy.js file in client/src. No need to import this anywhere. create-react-app will look for this directory

Add your proxies to this file.

const proxy=require("http-proxy-middleware")
module.exports=function(app){
    app.use(proxy(['/auth/google'],{target:"http://localhost:8888"}))}

We are saying that make a proxy and if anyone tries to visit the route /auth/google on our react server, automatically forward the request on to localhost:5000.

Yilmaz
  • 35,338
  • 10
  • 157
  • 202