Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check req.body empty or not in node ,express?

Below is my request body and which is sending from client side

var  credentials = {

"ConsumerData": {

            "ConsumerStoreId": "a",
            "ConsumerUserId": "a"
        },
        "CustomerData": {

            "CustomerId": "2345678890"
        },
        "ErnD": {
            "UID": "3",
            "TxnDt": "1"
        },

        "PurD": [{
                "ItemCode": "3456tghw3",
                "ItemEANCode": "223222122"

            },
            {
                "ItemCode": "8jghw3865",
                "ItemEANCode": "3334443222"

            }
        ]
}

for testing i am sending var credentials = {} empty credentials

In server side controller(node,express) i want to check req.body empty or not

if(!req.body)

{
 console.log('Object missing');
}
if(!req.body.ConsumerData.ConsumerStoreId)
  {
  console.log('ConsumerStoreId missing');
  }
 if(!req.body.CustomerData.CustomerId)
  {
  console.log('CustomerId missing');
  }
  if(!req.body.ErnD.UID)
  {
  console.log('UID missing');
  }
    console.log('outside'); 

i am checking everything but alwasys its printing outside only

like image 877
its me Avatar asked Mar 21 '17 08:03

its me


People also ask

How do you know if your body is empty?

Objects are considered empty if they have no own enumerable string keyed properties. Array-like values such as arguments objects, arrays, buffers, strings, or jQuery-like collections are considered empty if they have a length of 0. Similarly, maps and sets are considered empty if they have a size of 0.

What is req body in Nodejs?

The req. body object allows you to access data in a string or JSON object from the client side. You generally use the req. body object to receive data through POST and PUT requests in the Express server.


1 Answers

When the req.body is empty, it returns an empty object, as such, making !req.body return false even when it's empty. Instead, you should test for !Object.keys(req.body).length. What it will do is take every key from the object and count, if no keys where found it would return 0`. Then all we need to do is use the same method that we use on empty arrays, testing for !arr.length making it possible to receive a boolean stating it's fullness or the lack of it.

Then, we end up with the code:

router.post('/auth/signup', function(req, res) {
    if(!Object.keys(req.body).length) {
        // is empty
    } else if(!req.body.param1 || !req.body.param2 || !req.body.param3) {
        let params = [req.body.param1, req.body.param2, req.body.param3];
        let lackingParam = params.findIndex(param => !param === true) > 0 ? params.findIndex(param => !param === true) > 1 ? "req.body.param3" : "req.body.param2" : "req.body.param1";
        // lacking only lackingParam
    } else {
        // not empty
    }
});
like image 163
mmendescortes Avatar answered Sep 17 '22 19:09

mmendescortes