【问题标题】:RESTful API for HTTP DELETE doesnt check for nullHTTP DELETE 的 RESTful API 不检查 null
【发布时间】:2021-01-15 10:22:00
【问题描述】:

我目前正在为 Web 服务编写 RESTful API,但遇到了麻烦。我试图删除一封邮件,但首先我想检查邮件是否存在。我的问题是它不检查邮件是否为空并且不以 404 响应。我正在使用 expressmongoose

router.delete('/:id', (req, res) => {
    const { id } = req.params;
    Mail.findById(id)
      .exec()
      .then((mail) => {
        if (!mail) {
          console.log(mail) // returns null
          return res.status(404);
        }
      })
      .then(
        Mail.deleteOne({ _id: id })
          .exec()
          .then(() => {
            res.status(200).json({
              message: 'Mail deleted',
            });
          })
          .catch((err) => {
            res.status(500).json({ error: err });
          })
      );
  });

【问题讨论】:

  • 您能否在问题中添加有关预期行为与实际行为的信息?
  • 是的,对不起。如果邮件为空,我希望以 404 的 HTTP 状态代码进行响应。否则它应该通过删除找到的邮件继续

标签: javascript rest express mongoose http-delete


【解决方案1】:

我认为您必须在第一个 then 块中将代码的删除部分作为 else 语句。您没有返回下一个 then 块可以使用的任何内容。

你可以这样做:

Mail.findById(id)
      .exec()
      .then((mail) => {
        if (!mail) {
          console.log(mail) // returns null
          return res.status(404).send() //need to send response;
        }
        Mail.deleteOne({ _id: id })
          .exec()
          .then(() => {
            res.status(200).json({
              message: 'Mail deleted',
            });
          })
      }).catch((err) => {
            res.status(500).json({ error: err });
      })

专业提示:如果您不知道,请学习异步等待。代码看起来会更干净!

然后它看起来像这样:

router.delete('/:id', async (req, res) => {
    const { id } = req.params;

    try {
      const mail = await Mail.findById(id);
      if(!mail) {
         return res.status(404).send();
      }

      await Mail.deleteOne({_id: id});      
      res.status(200).json({
              message: 'Mail deleted',
            });
    } catch(e) {
      res.status(500).json({ error: err });
    }

【讨论】:

  • 谢谢。你是对的,使用 async/await 时它看起来更干净。我会仔细看看的。它也适用于你给我的代码
  • 太好了,很乐意为您提供帮助:)!
猜你喜欢
  • 1970-01-01
  • 2013-02-11
  • 1970-01-01
  • 1970-01-01
  • 2017-10-03
  • 2017-12-05
  • 2018-09-23
  • 1970-01-01
  • 2021-06-25
相关资源
最近更新 更多