[英]How to show logged on username in NodeJS/ExpressJS/Passport?
I want to display the username in case the user is logged in ( function 3
). 我想显示用户名,以防用户登录( function 3
)。 Initially, I only had function 1
. 最初,我只有function 1
。 I've changed function 1
into function 2
in order to display the username of the logged in user. 我已将function 1
更改为function 2
,以显示已登录用户的用户名。 I am not sure if this is the right way to do this, because I don't know if I need parameters res
and next
, and function next()
. 我不确定这是否是正确的方法,因为我不知道是否需要参数res
和next
以及函数next()
。 Any idea? 任何想法?
I am using NodeJS
, ExpressJS
and Passport
我正在使用NodeJS
, ExpressJS
和Passport
1. 1。
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return next()
} else {
res.redirect('/login')
}
}
2. 2。
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return true
}
return false
}
3. 3。
router.get('/', function(req, res) {
if (isLoggedIn) {
res.render('index', {
username: req.user.username
})
} else {
res.render('index')
}
})
You are pretty much doing the right but calling the method isLoggedIn
like a variable. 您几乎做对了,但是像变量一样调用isLoggedIn
方法。 I have corrected the same below. 我已经在下面更正了相同的内容。
2 . 2 。
function isLoggedIn(req, res, next) {
if (req.isAuthenticated()) {
return true;
}
return false;
}
3 . 3 。
router.get('/', function(req, res, next) {
if (isLoggedIn(req, res, next)) {
res.render('index', {
username: req.user.username
});
} else {
res.render('index');
}
});
Also, you can refactor the isLoggedIn
method as below. 另外,您可以按以下方式重构isLoggedIn
方法。
function isLoggedIn(req, res, next) {
return req.isAuthenticated();
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.