【发布时间】: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