【问题标题】:How do I make node respond with error if payload is empty如果有效负载为空,如何使节点响应错误
【发布时间】:2020-03-26 22:14:39
【问题描述】:

如果有效负载为空,我需要一个代码来响应错误。我该怎么做?

if(req.body !== {}){
      res.json(newUser)
    }else{
      res.status(400).json('fill in the necessary information')
    }

【问题讨论】:

  • 您的支票有什么问题?它是作为未定义的对象还是空对象{} 进来的?
  • 同样设置状态后需要res.send("whatever")

标签: javascript node.js reactjs express jsx


【解决方案1】:
if(req.body){
  res.json(newUser)
}else{
  res.status(400).json('fill in the necessary information')
}

【讨论】:

    【解决方案2】:

    检查req.body !== {} 总是正确的,因为您无法比较对象。您可以检查它是否未定义,然后检查键以了解它是否为空。像这样的:

    if(req.body && Object.keys(req.body).length !== 0){
      res.json(newUser)
    } else {
      res.status(400).json('fill in the necessary information')
    }
    

    阅读更多关于对象相等的信息here

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-06-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-12-01
      • 2019-10-17
      • 1970-01-01
      • 2014-03-30
      相关资源
      最近更新 更多