Express NodeJS | Express-messages,Express-validator和Connect-Flash不显示消息

时间:2018-03-25 10:59:28

标签: express pug connect-flash express-validator

这个问题到处都是,但基本上,每当你登录/退出时都应该显示消息,如果你没有填写正确的输入。

没有任何消息出现,我没有收到任何错误,但其他一切似乎都有效,我们将非常感谢您的帮助。

    // Express Session Middleware
app.use(session({
  secret: 'keyboard cat',
  resave: true,
  saveUninitialized: true,
  cookie: { secure: true }
}));


// Express Messages Middleware
app.use(require('connect-flash')());
app.use(function (req, res, next) {
  res.locals.messages = require('express-messages')(req, res);
  next();
});

// Express Validator Middleware
app.use(expressValidator({
  errorFormatter: function(param, msg, value) {
      var namespace = param.split('.')
      , root    = namespace.shift()
      , formParam = root;

    while(namespace.length) {
      formParam += '[' + namespace.shift() + ']';
    }
    return {
      param : formParam,
      msg   : msg,
      value : value
    };
  }
}));

这是注册部分

router.post('/register', function(req, res){
  const name = req.body.name;
  const email = req.body.email;
  const username = req.body.username;
  const password = req.body.password;
  const password2 = req.body.password2;

  req.checkBody('name', 'Name is required').notEmpty();
  req.checkBody('email', 'Email is required').notEmpty();
  req.checkBody('email', 'Email is not valid').isEmail();
  req.checkBody('username', 'Username is required').notEmpty();
  req.checkBody('password', 'Password is required').notEmpty();
  req.checkBody('password2', 'Passwords do not 
match').equals(req.body.password);

  let errors = req.getValidationResult();

if(errors){
    res.render('register', {
      errors:errors
    });
  } else {
    let newUser = new User({
      name:name,
      email:email,
      username:username,
      password:password
    });

    bcrypt.genSalt(10, function(err, salt){
      bcrypt.hash(newUser.password, salt, function(err, hash){
        if(err){
          console.log(err);
        }
        newUser.password = hash;
        newUser.save(function(err){
          if(err){
            console.log(err);
            return;
          } else {
            req.flash('success','You are now registered and can log in');
            res.redirect('/users/login');
          }
        });
      });
    });
  }
});

我正在使用帕格,这是消息部分

.messages
        each type in Object.keys(locals.messages)
          each message in Object.values(locals.messages)
            div(class="alert alert-"+type) #{message}

这就是我在布局中的内容

!= messages('message', locals)
      if errors
        each error, i in errors
          div(class="alert alert-danger") #{error.msg}

很抱歉,如果这令人困惑,如果我需要提供更多信息或解决任何问题,请告诉我。

0 个答案:

没有答案