如何将会话传递到Node / Express中的视图?

时间:2012-12-30 00:10:42

标签: node.js express

我正在使用Node / Express 3.0。但我不知道如何开会。特别是我不确定我是否正确使用routes / session.js中的以下内容。

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

以下是更多细节。

我在app.js中有这个

var express = require('express')
  , routes = require('./routes')
  , http = require('http')
  , path = require('path')
  ;

var app = express();

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'jade');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('testtest'));
  app.use(express.session({
    secret: 'testtest',
    maxAge: 3600000
  }));
  app.use(app.router);
  app.use(express.static(path.join(__dirname, 'public')));
});
...
require ('./routes/session')(app);
...
http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

在routes / session.js中

module.exports = function(app) {

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

  app.get('/session/new', function(req, res) {
    res.render('session/new', {title: "Log in"});
  });

  app.post('/session', function(req, res) {
    if (users[req.body.username] && 
      users[req.body.username].password === req.body.password) {
        req.session.user = users[req.body.username];
        res.redirect('/users');
      } else {
        res.redirect('/session/new')
      }
  });

  app.del('/session', function(req, res, next) {
    req.session.destroy();
    res.redirect('/users');
  });

};

我有这个观点。

- if (session.user) {

  p
    span Hello 
    span= session.user.name
    span= session
    span !
  p
    form(method="POST", action="/session")
      input(type="hidden", name="_method", value="DELETE")
      input(type="submit", value="Log out")

- } else {

  p
    a(href="/session/new") Login
    span  or 
    a(href="/users/new") Register

- }

但是这不会取得会话并且会出错。

1| > 2| - if (session.user) { 3| 4| p 5| span Hello  session is not defined

1 个答案:

答案 0 :(得分:6)

对于中间件工作方法,您需要确保在致电app.use之前完成安装中间件的app.use(app.router);电话。目前,您通过require('./routes/session')(app);电话后调用它:

require ('./routes/session')(app);
app.use(app.router);

要在没有中间件的情况下执行此操作,请更改res.render调用以传递您希望视图可用的本地session变量:

app.get('/session/new', function(req, res) {
  res.render('session/new', {title: "Log in", session: req.session});
});