Wednesday, 31 May 2017

express validator; error variable not defined within ejs

I have an issue that I've been trying to figure out for some time now, and was hoping someone may be able to point me in the right direction.

My variable (error) that I'm passing along in the res.render{} object, is unusable within my layouts file. The issue is logging as a reference error.

If I take the ejs code out, my error properly logs to the terminal; I'm just unable to use it within my layout file.

Following is the layout.ejs code, in part.

<% for(var i = 0; i < errors.length - 1; i++){ %>
  <li> <%= errors[i] %> </li>
<% } %>

and POST...

//POST route
app.post('/articles/add', function(req, res){

  req.assert('title', 'Enter title').notEmpty();
  req.assert('author', 'Enter author').notEmpty();
  req.assert('body', 'Enter an article').notEmpty();

  //get errors
  req.getValidationResult().then(function(err){


    if(err.isEmpty()){
      console.log(err);
      res.render('add_article',{
        title: 'Add Article',
        errors: err // <-
      });
    }

    else {

      let article = new Article();
      article.title = req.body.title;
      article.author = req.body.author;
      article.body = req.body.body;
      article.save(function(e){
        if(e) {console.log(e)}
        else{
          req.flash('success', 'Article Added');
          res.redirect('/');

        }
      });
    }

  });

Thanks for any help.



via gummyguppy

No comments:

Post a Comment