如何在节点中检查req.body是否为空,表示? [英] How to check req.body empty or not in node ,express?

查看:306
本文介绍了如何在节点中检查req.body是否为空,表示?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我的请求正文,从客户端发送

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"

            }
        ]
}

用于测试我发送 var credentials = {} 空凭据

在服务器端控制器(节点,快递)中我想检查req.body是否为空

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

推荐答案

ES2015:

if(req.body.constructor === Object && Object.keys(req.body).length === 0) {
  console.log('Object missing');
}

PRE ES2015:

function isEmpty(obj) {
    for(var prop in obj) {
        if(obj.hasOwnProperty(prop))
            return false;
    }
    return JSON.stringify(obj) === JSON.stringify({});
}

if(isEmpty(req.body)) {
    console.log('Object missing');
}

有关 pre es2015 风格的更多方式: https://coderwall.com/p/_g3x9q / how-to-check-if-javascript-object-is-empty

For more ways in a pre es2015 style: https://coderwall.com/p/_g3x9q/how-to-check-if-javascript-object-is-empty

这篇关于如何在节点中检查req.body是否为空,表示?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆