为 PassportJS 不工作创建 React App 代理来表达服务器

Create React App proxy to express server for PassportJS not working

花了几天时间尝试为我的 React 应用程序设置代理到我使用 passportjs 进行 gooogle 社交身份验证的 express 后端。

3000 端口上的 React 开发服务器 端口 5000 上的快速服务器

当我点击按钮时,它会重新加载页面,但不会启动 passportJS google 身份验证过程(即不会重定向到 oauth2 流程)。

<Button href='/auth/google'> Link Button </Button>

下面的关键代码片段应允许代理从 React 前端工作以表达 passportJS Oauth2 流程。

package.json

"proxy": "http://localhost:5000"

app.js

  <a href="auth/google/" target="">
    <Button> Link Button </Button>
  </a>

server.js

app.get('/auth/google',
    passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/userinfo.email', 
                                                'https://www.googleapis.com/auth/userinfo.profile',
                                                'openid'] }),
);
   

setupProxy.js

const proxy = require("http-proxy-middleware");

module.exports = function(app) {
    app.use(proxy('/auth', { target: 'http://localhost:5000/' }));
};

我最终不需要 package.json 代理条目。这些都是让一切都按预期工作的所有部分。

我在 /client 目录中有前端应用程序,这是我使用 create react app 的地方。

从 package.json 中的 create react app(客户端目录)我删除了它,因为 http-proxy-middleware 似乎需要 commonjs 导入 “类型”:“模块”,

setupProxy.js

const proxy = require("http-proxy-middleware");

module.exports = function(app) {
    app.use(proxy('/auth/google', { target: 'http://localhost:5000/' }));
};

App.js 使用 material UI 按钮

<Button href="/api/auth/google" variant="contained" color="primary">

Index.js 用于 passportJS 配置和 express 服务器

在 passportGoogle.strategy 选项中将其设置为与配置的其余部分一致

callbackURL: `/api/auth/google/callback`


app.get('/api/auth/google',
    passport.authenticate('google', { scope: ['https://www.googleapis.com/auth/userinfo.email', 
                                                'https://www.googleapis.com/auth/userinfo.profile',
                                                'openid'] }),
);
   
app.get('/api/auth/google/callback', 
    passport.authenticate('google', { failureRedirect: '/failed' }),
        function(req, res) {
            res.redirect('http://localhost:3000');
        }
);

Google 控制台

URI

http://localhost:3000

授权的重定向 URI

http://localhost:3000/api/auth/google/callback