如何公开会话变量来表达视图

时间:2016-01-08 11:15:02

标签: javascript node.js express express-session

我试图在EJS视图中访问会话变量,但面临很多问题。

要在本地访问req.session,请使用此处所述的中间件Accessing Express.js req or session from Jade template

var express = require('express');
var mongoose = require('mongoose');
var db = require('./models/db.js');

var routes = require('./routes/route.js');
var user = require('./routes/user.js');
var story = require('./routes/story.js');
var bodyParser = require('body-parser');

var session = require('express-session');
var cookieParser = require('cookie-parser');

mongoose.connect('mongodb://localhost/test');

var app = express();


app.use(function(req,res,next){
    res.locals.session = req.session;
    next();
});



app.set('view engine','ejs');

app.use(express.static(__dirname + '/public'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({extended:false}));
app.use(cookieParser());
app.use(session({secret:"qazwsxedcrfvtgbyhnujm"}));


app.get('/',routes.home);

app.get('/register',routes.register);
app.post('/newUser',user.doCreate);

app.get('/login',routes.login);
app.post('/authenticate',user.login);

app.get('/new-story',routes.newStory);
app.post('/add-story',story.addStory);


app.get('/stories/:story',story.getStory);
app.post('/stories/:slug/saveComment',story.saveComment);

var port = process.env.PORT || 3000;

var server=app.listen(port,function(req,res){
    console.log("Catch the action at http://localhost:"+port);
});

这是处理家庭路线的route.js

var mongoose = require( 'mongoose' );
var Story = mongoose.model( 'Story' );
exports.home=function(req,res){
             Story.find({}, function(err,stories){
                  res.render('home',{stories:stories});
              });
}

在home.ejs中,我通过检查是否设置了username属性来检查用户是否已登录或注释。

<% if( typeof(session.username) !== 'undefined' ) {%
<h1>Welcome</h1><%=session.username%>
<%}%>

但是,在访问主页面时,我收到错误消息 无法读取属性&#39;用户名&#39;未定义的 error

一旦用户通过身份验证,我就会在会话中设置用户名。

exports.login=function(req,res){
    var email=req.body.email;
    var password=req.body.password;

    User.findOne({email:email}, function(err,user){

      if(err){
        res.redirect("/login");
      }

     user.comparePassword(password,function(err,isMatch){
       if(isMatch && isMatch==true){
         console.log("Authentication Sucessfull");
         req.session.username=user.username;
         console.log("Got USer : "+req.session.username);
         res.redirect("/");
       }else{
         console.log("Authentication UnSucessfull");
         res.redirect("/login");
       }

     });

    });
  }

1 个答案:

答案 0 :(得分:1)

Express按照声明的顺序运行中间件。

你有这个:

app.use(function(req,res,next){
    res.locals.session = req.session;
    next();
});
...
app.use(session({secret:"qazwsxedcrfvtgbyhnujm"}));

您的中间件在会话中间件之前运行(它在它之前声明),因此您在会话中间件有机会创建res.locals.session之前创建req.session

尝试在会话中间件之后将中间件移动到

app.use(session({secret:"qazwsxedcrfvtgbyhnujm"}));
app.use(function(req,res,next){
    res.locals.session = req.session;
    next();
});