连接闪存中间件无法正常工作

时间:2012-11-07 00:26:31

标签: node.js express

我试图在我的express3应用程序中使用connect-flash。

我成功安装了包:

$ npm install connect-flash

我加入了它:

var flash = require('connect-flash');

设置中间件:

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

并使用它:

app.get('/admin', function(req, res) {   
    if(loggedIn === true) {      
      res.redirect('/admin/books');
    }
    else {      
      res.render('login', {message: req.flash('error') });
    }    
  });
  app.post('/admin', function(req, res) {    
    if((adminAccount.username === getCrypted(req.body.username)) && 
      (adminAccount.password === getCrypted(req.body.password))) {

      loggedIn = true;
      res.redirect('/admin/books');
    }
    else {
      req.flash('error', 'Woops, looks like that username and password are incorrect.');
      res.redirect('/admin');
    }
  });

但是我得到:TypeError: Object #<IncomingMessage> has no method 'flash'。我按照其github页面上的说明进行操作。我错过了什么?

1 个答案:

答案 0 :(得分:1)

颠倒顺序:

app.use(flash());

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