如何在ejs中获取会话值 [英] How to get the session value in ejs

查看:73
本文介绍了如何在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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆