我正在使用 express 3 中的新消息系统,并在处理和验证表单时发现了这个问题。提交无效表单时,提交失败,但不显示错误消息。再次提交时,会显示上次请求的错误消息。我尝试使用本地会话和 Redis 会话,它总是一样的。这是默认的快递项目:
应用程序.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>
<% } %>
- / 没有消息
- /你好显示'/'
- /world 显示“/你好”
- 重新加载显示“/世界”
这里有什么问题?