I use this code to check if user token is correct, and put user into req.locals
exports.isLoggedIn = async (req, res, next) => {
if (req.cookies.jwt) {
try {
const decoded = await promisify(jwt.verify)(
req.cookies.jwt,
process.env.JWT_SECRET
);
const currentUser = await User.findById(decoded.id);
if (!currentUser) {
return next();
}
if (currentUser.changedPasswordAfter(decoded.iat)) {
return next();
}
res.locals.user = currentUser;
return next();
} catch (err) {
return next();
}
}
next();
};
After that, I render the view. This is my header, name of the user should be displayed here, but it seems to be empty. There is a user, and it is not empty, but for some reason i cannot access directly his name using hbs
<nav >
<div >
{{#if user}}
<ul >
<li ><a href="/users/logout" data-abc="true">Log Out</a></li>
</ul>
<ul >
<li >
<div ><img src="https://i.imgur.com/EYFtR83.jpg"
width="30"></div>
</li>
<li ><a href="#" data-abc="true">
<span>{{user.name}}</span>
<i class='bx bxs-chevron-down'></i></a>
</li>
</ul>
{{else}}
<ul >
<li ><a href="/users/login" data-abc="true">Log In</a></li>
<li ><a href="/users/signup" data-abc="true">Sign Up</a></li>
</ul>
{{/if}}
</div>
Any ideas?
UPD Added hbs configuration and controller function that renders page
app.set('view engine', 'hbs');
hbs.registerPartials(__dirname "/views/partials");
app.engine("hbs", engine ({
layoutsDir: "views/layouts",
defaultLayout: "layout",
extname: "hbs"
}
));
Also, here is controller method, that renders page
exports.getHomePage = async (req, res, next) => {
res.render('home');
};
CodePudding user response:
Views in Express don't have access to the request object. They only have access to the data in the object passed as the locals parameter:
const locals = { put: "some data here" };
res.render('home', locals);
You aren't passing any data at all.
