警报在重新加载后仍然保持不变

时间:2017-10-11 10:24:59

标签: javascript express ejs

快递:

router.get('/polls/new', isLoggedIn, (req, res) => {
    res.render('new', {title: 'Create a new poll', route: 'new', isLoggedIn: req.isAuthenticated(), errors: req.session.errors});
    req.session.errors = null;
});

router.post('/polls', isLoggedIn, (req, res) => {
    req.check('title', 'Title must contain atleast 10 characters and must not exceed 100 charcters').isLength({min: 10, max: 100});
    var errors = req.validationErrors();
    console.log(errors);
    if (errors) {
        req.session.errors = errors;
        res.redirect('/polls/new');
    }

EJS:

<% if (errors)  { %>
<% errors.forEach((error) => { %>
    <div class="alert alert-danger alert-dismissible fade show" role="alert">
      <button type="button" class="close alert-dismissible" data-dismiss="alert" aria-label="Close">
        <span aria-hidden="true">&times;</span>
      </button>
      <strong>Error!</strong> <%= error.msg %>
    </div>
<% }); } %>

尝试在验证失败时显示警报消息。它工作得很好。但是当重新加载页面时,即使我将错误设为null,警报仍然会显示。

1 个答案:

答案 0 :(得分:0)

res.render的调用有效地结束了您的HTTP请求,因此在调用渲染后reqres发生的任何事情实际上都从未发生过。尝试在另一个变量中复制errors的值,如:

router.get('/polls/new', isLoggedIn, (req, res) => {
    let err = req.session.errors;
    req.session.errors = null;
    res.render('new', {title: 'Create a new poll', route: 'new', isLoggedIn: 
        req.isAuthenticated(), errors: err});
});