最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Express API - Verifying req.body elements - Stack Overflow

programmeradmin1浏览0评论

Am building an api using express and node.js.

I'm working on basic validation and want to verify items being passed in exist and are safe (done in addition to validation on client side).

So i have teh following:

router.post('/register', function(req, res) {

  for (var itemsFromBody in req.body){
    console.log(itemsFromBody);

}

However when i check the console all i see are the names of the Keys e.g. username, email etc, not the values themselves.

How do i obtain those?

Also I'll be doing validation on those eg making sure its not empty - do i need to follow a simple if-then statement or is there some nice npm package that exists that allows me to verify?

Thanks!

Am building an api using express and node.js.

I'm working on basic validation and want to verify items being passed in exist and are safe (done in addition to validation on client side).

So i have teh following:

router.post('/register', function(req, res) {

  for (var itemsFromBody in req.body){
    console.log(itemsFromBody);

}

However when i check the console all i see are the names of the Keys e.g. username, email etc, not the values themselves.

How do i obtain those?

Also I'll be doing validation on those eg making sure its not empty - do i need to follow a simple if-then statement or is there some nice npm package that exists that allows me to verify?

Thanks!

Share Improve this question asked Feb 11, 2016 at 16:24 userMod2userMod2 9,00217 gold badges73 silver badges134 bronze badges
Add a ment  | 

2 Answers 2

Reset to default 4
for (var itemsFromBodyIndex in req.body){
    if (req.body.hasOwnProperty(itemsFromBodyIndex)) {
       console.log(req.body[itemsFromBodyIndex]);
    }
}

This should work !

Useful links:

  • https://developer.mozilla/fr/docs/Web/JavaScript/Reference/Instructions/for...in
  • https://developer.mozilla/fr/docs/Web/JavaScript/Reference/Objets_globaux/Object/hasOwnProperty

And what about an error catcher into the loop if all of your fields are required ?

for (var itemsFromBodyIndex in req.body){
    if (req.body.hasOwnProperty(itemsFromBodyIndex)) {
        console.log(req.body[itemsFromBodyIndex]);

        if(req.body[itemsFromBodyIndex] == null){
            // handle empty field            
        }

    }
}

The for -- in will only give you keys, as you noticed above. You need to use those keys to get the values

for (var itemsFromBody in req.body){
    console.log("Key: " + itemsFromBody + " Value: " + req.body[itemsFromBody]);
}
发布评论

评论列表(0)

  1. 暂无评论