【问题标题】:Create React App proxy to express server for PassportJS not working创建 React App 代理来表达 PassportJS 的服务器不工作
【发布时间】:2021-05-13 15:51:54
【问题描述】:

花了几天时间尝试为我的 react 应用程序设置代理到我的 express 后端,我在其中使用 passportjs 进行谷歌社交身份验证。

在 PORT 3000 上反应开发服务器 端口 5000 上的快速服务器

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

<Button href='/auth/google'> Link Button </Button>
  • curl 正在正确代理从端口 3000 到 5000 的调用
  • 当我直接转到我在此处创建的快速服务器端点时,PassportJS 进程正常工作:http://localhost:5000/auth/google

下面的关键代码片段应该允许代理从反应前端工作以表达 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/' }));
};

【问题讨论】:

    标签: reactjs express proxy passport.js create-react-app


    【解决方案1】:

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

    我在 /client 目录中有前端应用程序,这是我用来创建反应应用程序的地方。

    从创建反应应用程序(客户端目录)中的 package.json 我删除了它,因为 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 使用材质 UI 按钮

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

    用于 passportJS 配置和快递服务器的 Index.js

    在 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');
            }
    );
    

    谷歌控制台

    URI

    http://localhost:3000

    授权的重定向 URIs

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2016-05-04
      • 1970-01-01
      • 2013-04-18
      • 2020-02-14
      • 2019-10-01
      • 1970-01-01
      • 2018-10-24
      • 2017-08-30
      相关资源
      最近更新 更多