Node Express Flash消息不起作用

时间:2015-12-15 03:27:54

标签: node.js express

我不知道为什么快递消息不起作用。我在app.js中指定了它,在路由器/控制器和视图中指定了它。

这是我app.js的一部分:

var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var exphbs = require('express-handlebars');
var expressValidator = require('express-validator');
var flash = require('connect-flash');
var session = require('express-session');
app.use(flash());
app.use(require('connect-flash')());

app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);

  if(req.url == '/'){
    res.locals.isHome = true;
  }
  next();
});

这是我指定flash消息的路线:

router.post('/login', passport.authenticate('local', {failureRedirect: '/', failureFlash: 'Invalid username or password'}), function(req, res){
    console.log(req.body);
    console.log('Authentication Successful');
    req.flash('success', 'You are logged in');
    var usertype = req.user.type;
    res.redirect('/'+ usertype + 's/classes');
});

router.get('/logout', function(req, res){
    req.logout();
    req.flash('success', "You have logged out");
    res.redirect('/');
})

这是我的车把视图,我有消息标签:

<div class="col_12">
    <div class="col_9">
        {{{messages}}}
        {{#if errors}}
            {{#each errors}}
                <div class="notice error">
                    <i class="icon-remove-sign icon-large"></i>
                    {{msg}}
                    <a href="#close" class="icon-remove"></a>
                </div>
            {{/each}}
        {{/if}}
    {{{body}}}

1 个答案:

答案 0 :(得分:3)

connect-flash 将消息保存到会话中。在添加flash中间件之前,您需要使用 express-session

app.use(session());
app.use(flash())