2017-01-16 173 views
0

我创建了一个路由作为验证我所有的路由,我希望这能够处理所有请求并验证它们,问题是我想检查属性是否在请求中,而不是数据只是属性,让我们说用户有一个电子邮件,但其他人没有,我想检查身体是否有电子邮件属性运行某些代码来验证此电子邮件。nodejs express mongoose mongodb

我怎么知道,如果

req.body.email; 

在身体?

var express = require('express'); 
var router = express.Router(); 


router.use('/', function(req, res, next) { 
      var record = req.body.record, 
       email = record.email, 
       phone_number = record.phone_number, 
       school_id = req.body.schoolId; 

      console.log("validator"); 

      if (record) { 

       if (what is the condition here to check 
        if the body has email) 

        req.asyncValidationErrors() 
        .then(function() { 
         next(); 

        }).catch(function(errors) { 
         if (errors) { 
          res.json({ 
           status: "error", 
           message: "please make sure your data is correct and your email and phone number are not valid" 
          }); 
          return; 
         } 
        }); 
      }); 


     module.exports = router; 

回答

0

要知道email是否在身上,你需要检查undefined。访问时,不在身体内的属性将为您提供undefined

if (body.email === undefined) { 
    console.log('email attribute is not in the body, hence it comes here'); 
    return res.json({ 
     status: "error", 
     message: "please make sure your data is correct and your email is valid" 
    }); 
} 

如果你已经在你的应用程序中登录。

let _ = require('lodash'); 

let body = req.body; 

if(_.isUndefined(body.email)) { 
    console.log('email attribute is not in the body, hence it comes here'); 
    return res.json({ 
     status: "error", 
     message: "please make sure your data is correct and your email is valid" 
    }); 
} 
+0

这将执行上body.email的所有falsy(https://developer.mozilla.org/de/docs/Glossary/Falsy)值的块,不只是当它不存在。 – Florian

+0

@Florian是的。你是对的。感谢您指出。我已更新。 – Sridhar

+1

我认为lodash在这里是完全矫枉过正,为什么不(body.email === undefined)?查看isUndefined的来源:https://github.com/lodash/lodash/blob/4.17.4/lodash.js#L12212 – DevDig