Alert keeps staying even after reload

Express:

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>
<% }); } %>

Am trying to show alert messages when the validation fails. It works perfectly fine. But when the page is reloaded the alert message still shows up even if I made the errors null.

1 answer

  • answered 2017-10-12 00:11 ruedamanuel

    The call to res.render effectively ends your HTTP request, so anything that happens to req or res after render has been called will effectively have never happened. Try duplicating the value of errors in another variable like:

    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});
    });