页面刷新时未定义 Sails.js 会话
问题描述:
在我的sails.js 应用程序中,我正在设置这样的会话
In my sails.js application i am setting up session like this
req.session.userId="hello";
console.log(req.session.userId);
在第一个请求之后我隐藏了这一行 req.session.userId="hello";
after the first request i hide this line req.session.userId="hello";
之后 console.log(req.session.userId)
返回 undefined
答
在没有看到更多控制器代码的情况下很难,但是您设置的会话属性只会在完成控制器操作后才会被处理到会话中 - 例如返回视图或 json.
Tough without seeing more of your controller code, but the session property you are setting is only going to be processed into session upon completing the controller action - e.g. returning a view or json.
试试:
if(req.session && req.session.userId){
//This user has an active session already so we have a userid
sails.log.info(req.session.userId);
else{
//Must be the first time this action was executed
req.session.userId = 'hello';
}
res.view('index');
其中 index 是 ejs 视图的名称.如果您从不返回任何内容,则永远不会设置会话属性.
where index is the name of your ejs view. If you never return anything then the session property is never set.