简体   繁体   English

如何在NodeJS / ExpressJS / Passport中显示登录的用户名?

[英]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() . 我不确定这是否是正确的方法,因为我不知道是否需要参数resnext以及函数next() Any idea? 任何想法?

I am using NodeJS , ExpressJS and Passport 我正在使用NodeJSExpressJSPassport

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.

相关问题 用户使用cakephp登录时如何显示用户名? - how to show username when user is logged in with cakephp? Express.js如何在用户登录时显示/隐藏div - Expressjs how to show / hide a div in case user its logged 使用Passport JS获取当前登录的用户名? - Get current logged in username using Passport JS? 如何使用 HTML 和 nodejs 显示用户名? - How to show username using HTML and nodejs? 如何使用Node.js和ExpressJS在mysql上显示数据 - How can I show data on mysql with nodejs and expressjs 如何使用Passport和NodeJS在angularJS前端中显示用户信息 - How to show user information in angularJS frontend with Passport and nodeJS NodeJS expressJS上载穆特尔和护照,并将文件保存到MongoDB - NodeJS expressJS upload and save file to MongoDB with multer and passport (Nodejs, expressjs, mongodb) UnhandledPromiseRejectionWarning: TypeError: 无法读取未定义的属性“用户名” - (Nodejs, expressjs, mongodb) UnhandledPromiseRejectionWarning: TypeError: Cannot read property 'username' of undefined 如何检查使用ExpressJS和Mongoose登录的用户? - How to check user logged in with ExpressJS and Mongoose? 如何在 Expressjs 上捕获错误的用户名或密码? - How to catch wrong username or password on Expressjs?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM