用于HTTP DELETE的RESTful API不检查null

问题描述

我目前正在为Web服务编写RESTful API,但遇到麻烦。我正在尝试删除邮件,但首先我想检查邮件是否存在。我的问题是,它不检查邮件是否为空,并且不响应 404 。我与 express 猫鼬

一起工作 @H_404_12@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 }); }) ); });

解决方法

我认为您必须先删除代码中的删除部分,然后将其作为else语句阻塞。您不会返回next 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 });
    }