【问题标题】:express validator; error variable not defined within ejs快速验证器;错误变量未在 ejs 中定义
【发布时间】:2017-05-31 22:01:03
【问题描述】:

我有一个问题,我一直在尝试解决一段时间,希望有人能指出我正确的方向。

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

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

以下是部分 layout.ejs 代码。

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

然后发布...

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

        }
      });
    }

  });

感谢您的帮助。

【问题讨论】:

    标签: javascript node.js express ejs


    【解决方案1】:

    据我所知,您的代码中有两个错误。首先,if(err.isEmpty()),当 err 为空时,您正在尝试发送 err!另一个是使用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>"}
    ]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-21
      • 1970-01-01
      • 1970-01-01
      • 2019-09-27
      • 1970-01-01
      相关资源
      最近更新 更多