为什么我仍然得到 200 响应状态代码而不是 404?

Why I still get the 200 response status code instead of 404?

我只是使用 sequelize 对 mysql 进行删除查询。

const model = require('../../../config/model/index');
const controller = {};

controller.drop =  async function(req, res) {
  try {
    await model.activitys.destroy({
      where: {
        id: req.params.id
      }
    })
    check_id = model.activitys.findAll({
      where: {
        id: req.params.id
      }
    })
    if(check_id!=null){
      res.status(200).json({
        status: "Success",
        message: "Success",
        data: {}
      })
    }else{    
      res.status(404).json({
        status: "Not Found",
        message: `Activity with ID ${id} Not Found`,
        data: {}
      })    
    }
  } catch (error) {
    res.status(404).json({
      status: "Error",
      message: error.message
    })
  }
}

module.exports = controller;

我想从id参数中删除DB上的数据,是删除数据的工作。但是当我尝试通过我的数据库中不存在的 id 删除时,它仍然得到 200 状态代码。

如果数据库中不存在数据,如何使 return 404 状态代码?

如果您想检查数据库中是否存在 单个 记录,请使用 findOnefindByPk 而不是 findAllfindAll 总是 returns 一个数组(无论是否为空),这意味着它总是不等于 null:

check_id = model.activitys.findOne({
      where: {
        id: req.params.id
      }
    })