[英]How to flash a user's username after a successful login using Passport.js?
I am trying to flash the message "Welcome back "username here" " to a user once they have successuly logged in to the website.我试图在用户成功登录网站后向他们显示消息“欢迎回到‘这里的用户名’”。
The problem is that logging in with passport is not a regular request and response, the authentication happens as an argument to the post request.问题是使用护照登录不是常规请求和响应,身份验证作为 post 请求的参数发生。 Below you can find my code:
您可以在下面找到我的代码:
var express = require("express");
var router = express.Router();
var user = require("../models/user");
var passport = require("passport");
router.get('/register', (req,res) =>{
res.render('register');
});
router.post('/register', (req,res) =>{
user.register(
new user({username: req.body.username}),
req.body.password,
(err, newUser) => {
if(err){
req.flash("error", err.message);
return res.redirect("/register");
}
passport.authenticate("local")(req, res, function(){
req.flash("success", "Successfully registered, welcome "+user.username.charAt(0).toUpperCase() + user.username.slice(1)+"!");
res.redirect("/");
});
}
);
});
router.get('/login', (req,res) =>{
res.render('login');
});
router.post('/login', passport.authenticate("local",{
successRedirect: "/",
failureRedirect: "/login",
failureFlash: true,
successFlash: 'Welcome back!'//HERE IS WHERE I AM INTERESTED
}), (req,res) =>{
});
router.get('/logout', (req,res) =>{
req.logout();
req.flash("success", "Successfully Logged Out")
res.redirect("/");
});
module.exports = router;
In the second argument to router.post
, call passport.authenticate
to handle the failureRedirect and failureFlash message.在
router.post
的第二个参数中,调用passport.authenticate
来处理 failureRedirect 和 failureFlash 消息。 Then, for the third argument, write your callback function with req and res.然后,对于第三个参数,使用 req 和 res 编写回调函数。 In the body of this function is where you'll handle the "success" flash message and you'll have access to your username on the request object.
在此函数的主体中,您将处理“成功”闪存消息,并且您将可以访问请求对象上的用户名。 And then you can do your res.redirect.
然后你可以做你的 res.redirect。
router.post(
"/login",
passport.authenticate("local", {
failureRedirect: "/login",
failureFlash: true
}),
(req,res) => {
req.flash("success", "Welcome back!"//add your username variable here);
res.redirect("/home");
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.