2017-01-16 76 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

相關問題