React and Nest.js google auth return CORS Error

1.7k Views Asked by At

I'm using in React of library "react-google-login": "^5.2.2" and in Nest.js: "passport-google-oauth20": "^2.0.0". In Nest.js google auth work correctly, but I have a problem on front-end site. When I click on button "Sign in with Google" and I loggin to google. Google auth return error cors:

Access to XMLHttpRequest at 'https://accounts.google.com/o/oauth2/v2/auth?response_type=code&redirect_uri=http%3A%2F%2Flocalhost%3A7000%2Fauth%2Flogin-google%2Fredirect&scope=email%20profile&client_id=XXXXX.apps.googleusercontent.com' (redirected from 'http://localhost:7000/auth/login-google') from origin 'http://localhost:3001' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource.

I'm trying fix this problem by add proxy to React (docs):

File src/setupProxy.js:

const createProxyMiddleware = require('http-proxy-middleware')

module.exports = function (app) {
  app.use(
    '/auth/login-google',
    createProxyMiddleware({
      target: 'http://localhost:7000',
      changeOrigin: true,
    }),
  )
}

But still I have this same CORS error.

React - http://localhost:3001
Nest.js - http://localhost:7000

How I can fix it?

EDIT:

I found this answer. I change action onClick on button "Sign in with Google" to:

window.location = 'http://localhost:7000/auth/login-google'

Now I don't get CORS error. Nest.js return me data about user (as I wanted, it's work correctly) but I don't know how I can listen in React when user is logged in. Because now when user click "Sign in with Google" (when the user logs in correctly) then the browser redirects to the address:

http://localhost:7000/auth/login-google/redirect?code=4%2F0AY0e-g7UsKrAyhmnc3xQBT3oE9ck9bCfuuO7lX9RJxh9JuRrZfdFPCaVZsRppapRfanGlw&scope=email+profile+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.profile+openid+https%3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=none

I'm trying using history.location but not work, because it's not address of React.

1

There are 1 best solutions below

0
Khanh Nguyen On

I use NestJS and Angular. This is how I fixed the CORS error. Please do it like this:

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import * as cors from 'cors';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.use(cors({
    origin: 'http://localhost:4200'
  }));
  await app.listen(parseInt(process.env.PORT) || 3000);
}
bootstrap();