如何在ejs中获取会话值 [英] How to get the session value in ejs
问题描述
我正在使用会话(使用Express和Nodes)制作一个登录模块. 用户登录后,我将用户保存在会话中.
I am making a login module using session(using express and nodes). When the user has logged in, I save the user in the session.
req.session.user= ...
如何在.ejs视图中获取会话值,如:
How can I get the session value in a .ejs view like:
<label>
您好!<%= req.session.user.username %>
</label>
但这是行不通的.
我可以这样做:
router.get('/home',function(req, res){
var val = req.session.user;
res.render('home',{user:val});
});
.ejs:
<p>
您好!<%= user.username %>
</p>
但这太麻烦了. 更好的方法是什么?
But this is so troublesome. What is the better way to do it?
(在php中,我只能使用$ _SESSION在视图文件中获取值.)
(In php, I can just use $_SESSION to get the value in a view file.)
推荐答案
您可以使用 res.locals
将特定数据公开给所有模板.
You can use res.locals
to expose particular data to all templates.
根据您的情况,您可以将以下中间件添加到Express中:
In your situation, you could add the following middleware to Express:
app.use(function(req, res, next) {
res.locals.user = req.session.user;
next();
});
这将在所有模板中提供一个user
变量.
This will make a user
variable available in all your templates.
您确实需要确保在设置了 req.session
之后添加中间件(通常是在将express-session
添加到中间件链中之后).
You do need to make sure that you add that middleware after req.session
has been set (which is usually after express-session
has been added to the middleware chain).
这篇关于如何在ejs中获取会话值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!