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 badges2 Answers
Reset to default 4for (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]);
}
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1745091630a4610726.html
评论列表(0条)