【问题标题】:How can I send the user saved in passport from the backend server to the React frontend server?如何将保存在护照中的用户从后端服务器发送到 React 前端服务器?
【发布时间】:2021-09-09 12:28:00
【问题描述】:

我在 React 中使用一个处理逻辑的后端服务器和一个前端服务器。我需要的是将登录的用户从后端服务器发送到前端服务器。但首先,我将解释用户登录后我的代码流如何以基本方式工作。

passport.use('local-signin', new LocalStrategy({
  usernameField: 'celnumber',
  passwordField: 'celnumber',
  passReqToCallback: true
  }, async (req, names, celnumber, done) => {
    const user = await userController.findByCelNumber(celnumber);
    if(!user) {
      return done(null, false, localStorage.setItem('failureMessage', 'El número ingresado no existe.'));
  }
  localStorage.setItem('successMessage', 'Te has logueado satisfactoriamente.')
  return done(null, user);
}));

登录成功后,会从successRedirect重定向到前端服务器:

router.post("/login", passport.authenticate("local-signin",
   {
     successRedirect: "http://localhost:3001",
     failureRedirect: "/users/login",
     passReqToCallback: true
   }
));

澄清successRedirect:" http: // localhost: 3001 " 只是为了让护照不会给我带来任何错误,但我根本没有真正使用它。我正在通过如下所示的 window.location.href 进行重定向。

最后,我的自定义钩子useFormHelper重定向前端服务器以呈现初始页面。

if(type === "login") {
   e.preventDefault();
   await axios.post('http://localhost:3000/users/login', form).then(async function (response){
      alert("Logueo completado satisfactoriamente.")
      window.location.href = "http://localhost:3001/";
   });
}

那么我的问题是,如何将登录到护照的用户从后端服务器本身发送到 React 前端服务器?

我在类似的帖子中看到我可以使用我的 windows.location.href 并将其传递给用户,例如:window.location.href =" http: // localhost: 3001 / "+ user,但理论上它不是很安全。 我还想到通过 succesRedirect 发送用户,但我没有“req”来发送护照 req.user。 successRedirect:" http: // localhost: 3001 "+ req.user,

我希望我已经正确解释了自己,不要犹豫,问我任何问题。谢谢。

【问题讨论】:

    标签: node.js reactjs frontend passport.js backend


    【解决方案1】:

    router.post 中添加一个回调函数,您将在其中将 req 和 res 作为参数:

    router.post("/login", passport.authenticate("local-signin",
       {
         successRedirect: "http://localhost:3001",
         failureRedirect: "/users/login",
         passReqToCallback: true
       }
    ), (req, res)=>{
            // If you use "Content-Type": "application/json"
            // req.isAuthenticated is true if authentication was success else it is false
            res.json({auth: req.isAuthenticated()});
    });
    

    在 then 函数的前端,你可以有这样的参数:

    axios.post(Your code).then((res)=>res.data.auth); // res.data will be the object that was sent from backend
    

    【讨论】:

    • 感谢 Luka,它运行良好。另一方面,我必须在前端引用res.config.data 而不是res.data.auth,但我还是有我的用户对象。再次感谢!
    猜你喜欢
    • 2021-06-12
    • 1970-01-01
    • 2020-12-29
    • 1970-01-01
    • 1970-01-01
    • 2021-02-15
    • 1970-01-01
    • 2018-04-02
    • 2020-03-14
    相关资源
    最近更新 更多