2

我正在玩 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
4

1 回答 1

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});
});
于 2012-12-30T02:16:04.570 回答