在Sailsjs视图中访问会话变量 [英] Accessing session variables in sailsjs view

查看:71
本文介绍了在Sailsjs视图中访问会话变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Sailsjs和Nodejs很陌生。我正在尝试创建一个身份验证页面,在该页面中,对用户进行身份验证之后,我想设置

I am quite new to sailsjs and nodejs. I am trying to create an authentication page, wherein once a user is authenticated, I want to set

req.session.user = user.id
req.session.authenticated = true

然后我需要访问这些值在我的主要layout.ejs文件中。我通过使用

I then need to access these values within my main layout.ejs file. I have done so by using

res.locals.user = _.clone( req.session.user )

但是,我注意到必须在每个控制器的每个函数中调用此克隆方法,以使我能够能够从视图中访问用户。是否有更好的方法来访问sailsjs globbaly中的会话变量,而不必在每个控制器中克隆req.session。我在做什么的示例可以在这里找到:

However, I noticed that this clone method has to be called in every function of every controller so as to allow me to be able to access the user from within the views. Is there a better way of accessing session variables in sailsjs globbaly, without having to clone the req.session in every controller. An example of what I am doing can be found here:

http://pastebin.com / HyE2H4Kq

如您所见,我在控制器内各种功能的开头调用了clone方法。

As you can see, I have called the clone method at the beginning of various functions within the controller.

推荐答案

默认情况下,视图中可以使用 req 对象,除非您覆盖 res.locals 完全。因此,您可以在视图中使用<%= req.session.user%> 访问会话变量(如果使用的是EJS)。您不必将其明确复制到本地用户中。

The req object is available in your views by default, unless you overwrite res.locals completely. So you can access a session variable in your view with <%=req.session.user%> (if you're using EJS). You don't have to copy it explicitly into your locals.

这篇关于在Sailsjs视图中访问会话变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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