1

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

在 '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 访问 XMLHttpRequest来自源“http://localhost:3001”的 .apps.googleusercontent.com'(重定向自“http://localhost:7000/auth/login-google”)已被 CORS 策略阻止:无“访问控制-请求的资源上存在 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

我该如何解决?

编辑:

我找到了这个答案。我将onClick“使用 Google 登录”按钮上的操作更改为:

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%2Fauth%2Fuserinfo.profile+openid+https% 3A%2F%2Fwww.googleapis.com%2Fauth%2Fuserinfo.email&authuser=0&prompt=none

我正在尝试使用history.location但不工作,因为它不是 React 的地址。

4

0 回答 0