【问题标题】:Why I still get the 200 response status code instead of 404?为什么我仍然得到 200 响应状态码而不是 404?
【发布时间】:2022-02-12 17:55:18
【问题描述】:

我只是用 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 状态代码。

如果数据库中不存在数据,如何使其返回 404 状态码?

【问题讨论】:

    标签: javascript mysql node.js sequelize.js


    【解决方案1】:

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

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

    【讨论】:

    • 我已经使用了findOne,但它仍然得到 200 状态响应。我的代码有错误吗?
    • 哦,它的工作,只是在destroy()之前更改DB上的检查数据。谢谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-05-08
    • 2020-05-05
    • 1970-01-01
    • 1970-01-01
    • 2021-10-04
    相关资源
    最近更新 更多