2017-05-31 26 views
0

我有一个问题,我一直试图找出一段时间,并希望有人能够指出我在正确的方向。表示验证器;错误变量未在ejs中定义

我在res.render {}对象中传递的变量(错误)在我的布局文件中不可用。该问题被记录为参考错误。

如果我把ejs代码取出,我的错误会正确地记录到终端上;我只是无法在我的布局文件中使用它。

以下是layout.ejs代码的一部分。

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

和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('/'); 

     } 
     }); 
    } 

    }); 

感谢您的帮助。

回答

0

正如我看到你的代码中有两个错误。首先,if(err.isEmpty()),当错误是空的,那么你正试图发送错误!另一种是使用req.getValidationResult(),它将用结果object解决而不是array。以下是可能有帮助的代码。

//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(result){ 


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

    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('/'); 

     } 
    }); 
    } 

}); 

而且result.array()会产生这样的事情:

[ 
    {param: "email", msg: "required", value: "<received input>"}, 
    {param: "email", msg: "valid email required", value: "<received input>"}, 
    {param: "password", msg: "6 to 20 characters required", value: "<received input>"} 
]