Express 3会话始终是一个请求

时间:2012-08-13 19:07:18

标签: node.js session express

我正在使用express 3中的新消息系统,并在处理和验证表单时发现了这个问题。提交无效表单时,提交失败,但没有显示错误消息。再次提交时,会显示上一个请求的错误消息。我尝试使用本地会话和Redis会话,它总是一样的。这是默认快递项目:

app.js

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

var app = express();

app.response.message = function(type, msg){
  // reference `req.session` via the `this.req` reference
  var sess = this.req.session;
  // simply add the msg to an array for later
  sess.messages = sess.messages || [];
  sess.messages.push({type: type, msg: msg});
  return this;
};

app.configure(function(){
  app.set('port', process.env.PORT || 3000);
  app.set('views', __dirname + '/views');
  app.set('view engine', 'ejs');
  app.use(express.favicon());
  app.use(express.logger('dev'));
  app.use(express.bodyParser());
  app.use(express.methodOverride());
  app.use(express.cookieParser('your secret here'));
  app.use(express.session());
  app.use(express.static(path.join(__dirname, 'public')));
  app.use(function(req, res, next) {
    console.log('req.session', req.session.messages);
    var msgs = req.session.messages || [];
    res.locals({
      messages: msgs,
      hasMessages: !! msgs.length
    });
    req.session.messages = [];
    next();
  });
});

app.configure('development', function(){
  app.use(express.errorHandler());
});
app.get('*', function(req, res, next) {
  res.message('hello', req.url);
  next();
});
app.get('/', function(req, res) {
  res.render('index', { title: 'Express' });
});
app.get('/hello', function(req, res) {
  res.render('index', { title: 'Express' });
});
app.get('/world', function(req, res) {
  res.render('index', { title: 'Express' });
});
http.createServer(app).listen(app.get('port'), function(){
  console.log("Express server listening on port " + app.get('port'));
});

索引体添加:

<% if (hasMessages) { %>
  <ul id="messages">
    <% messages.forEach(function(msg){ %>
      <li class="<%= msg.type %>"><%= msg.msg %></li>
    <% }) %>
  </ul>
<% } %>
  1. /没有消息
  2. / hello显示'/'
  3. / world shows'/ hello'
  4. reload shows'/ world'
  5. 这里有什么问题?

1 个答案:

答案 0 :(得分:4)

如果你不想推迟它们,你根本不需要使用会话,在这种情况下,重点是推迟下一个渲染的消息。当中间件填充“messages”和“hasMessages”时,除非先前的请求填充它们,否则它实际上没有任何内容。这通常用于推迟msgs码,例如“已成功更新用户”