React 和 Nest.js google auth 返回 CORS 错误

问题描述 投票:0回答:1

我在库的 React

"react-google-login": "^5.2.2"
和 Nest.js 中使用:
"passport-google-oauth20": "^2.0.0"
。在 Nest.js 中,谷歌身份验证工作正常,但我在前端站点上遇到问题。当我单击“使用 Google 登录”按钮并登录到 google 时。 Google 授权返回错误 cors:

访问 XMLHttpRequest 在 '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' (重定向自“http://localhost:7000/auth/login-google”)来自 来源 'http://localhost:3001' 已被 CORS 策略阻止:否 请求中存在“Access-Control-Allow-Origin”标头 资源。

我正在尝试通过向 React 添加代理来解决此问题(docs):

文件

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,
    }),
  )
}

但我仍然有同样的 CORS 错误。

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

我该如何解决?

编辑:

我找到了这个answer。我将“使用 Google 登录”按钮上的操作

onClick
更改为:

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

现在我没有收到 CORS 错误。 Nest.js 向我返回有关用户的数据(如我所愿,它工作正常)但我不知道当用户登录时我如何在 React 中收听。因为现在当用户单击“使用 Google 登录”时(当用户正确登录)然后浏览器重定向到地址:

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

我正在尝试使用

history.location
但没有用,因为它不是 React 的地址。

reactjs cors nestjs google-authentication react-google-login
1个回答
0
投票

我使用 NestJS 和 Angular。这就是我修复 CORS 错误的方法。请这样做:

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();
© www.soinside.com 2019 - 2024. All rights reserved.