I am trying to implement a pretty basic error message for a login page I am trying to build. The code for the post request is as follows.

app.post('/login',function(req,res){
  User.findOne({username:req.body.user.username},function(err,info){
  if(err){
    req.flash('error','There was an error on our end. Sorry about that.');
    res.redirect('/');
  }

  if(info==null){
    req.flash('error', 'Incorrect Username. Please try again, or make an account');
    res.redirect('/login');
  }
  else{
    if(req.body.user.password==info.password){
      res.redirect('/users/' + info.username);
    }
    else{
      req.flash('error', 'Incorrect Password');
      res.redirect('/login');
    }
  }
});
});

I never see the error message when I trigger the null case, although the redirect does occur. My get method for the route is as follows:

app.get('/login',function(req,res){
   res.render('login',{
     title: 'Login'
   });
});
有帮助吗?

解决方案

You need to pass the flash messages to your template, and render them yourself there:

app.get('/login',function(req,res){
   res.render('login',{
     title  : 'Login',
     errors : req.flash('error')
   });
});

If you're using EJS templates (for example), you check if errors contains a value, and show it:

<% if (errors) { %>
  <p class="error"><%= errors %></p>
<% } %>
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top