简体   繁体   中英

Show logged in user name using Node js + Express 4 + Passport

I have a Node Js + Express 4 + express-handlebars app. I am using Passport for local authentication. I want to show the logged in username on the top of the page. Right now I have to define it on each page render.

res.render('somePage', {
    title : 'My page',
    userName : req.user.Name,
});

I did some research and found a similar StackOverflow question (two year old question where he was using Express3) where the suggested solution was to use app.locals to set res.locals username variable.

app.use(function (req, res, next) {
    res.locals = {
        user: req.user
    };
    next();
});

{{user.Name}}

I tried that but it did not work for me.

How can I set the username once after login so I do not have to include it on every page render?

try adding .user after locals

res.locals.user = {user: req.user};

Hope this helps :)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM