gpt4 book ai didi

javascript - 如何在 Node 中检查 req.body 是否为空,express?

转载 作者:搜寻专家 更新时间:2023-10-31 22:56:10 25 4
gpt4 key购买 nike

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

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 = {} empty credentials

在服务器端 Controller (node,express)中,我想检查 req.body 是否为空

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');

我正在检查所有内容,但总是只在外面打印

最佳答案

ES2015:

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

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

关于javascript - 如何在 Node 中检查 req.body 是否为空,express?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42921727/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com