1

I am trying to use a session variable in my view file. My controller code is like this

User.find()
.where({ username: username })
.where({ password: password })
.exec(function(err, users) {
  if(users.length == 1){
    req.session.user_detail = users; 
    res.redirect('/member');
  }else{
    console.log(err);  
  }
});

I want to use the req.session.user_detail in my member.ejs file.

Chad
  • 2,161
  • 1
  • 19
  • 18
Nakarmi
  • 453
  • 1
  • 6
  • 16

3 Answers3

4

For the record, in case someone stumbles onto this question instead of this one, req.session is indeed available by default in your Sails views. So you can just do

<%= JSON.stringify(req.session.user_detail) %>

in your view; there's no need to pass it explicitly in res.locals. You can also loop through the users with:

<%  req.session.user_detail.forEach(function(user_detail) { %>
<%=   JSON.stringify(user_detail) %>
<%  }) %>
Community
  • 1
  • 1
sgress454
  • 24,870
  • 4
  • 74
  • 92
  • Your reply was helpful but it just displays [object][object]. I used <%= JSON.stringify(req.session.user_details) %> and it worked. – Nakarmi Mar 09 '14 at 05:23
0

I myself am new to nodejs/sailjs but from what I understand, req.session is not exposed to the views. The way I have been passing data from the session to the views is as follows:

res.locals.user_detail= _.clone(req.session.user_detail);

You can then access res.locals.user_detail from within your view. I do not know if this is the right way to do it, but this is what I have been using and has worked for me. I hope this helps you.

kushaldsouza
  • 710
  • 5
  • 12
  • 36
0

Just try accessing like that

session.user_detail
icebreaker
  • 1,224
  • 17
  • 33