【问题标题】:Not able to get my setup 404 status code, instead getting 500 status code for incorrect id无法获取我的设置 404 状态代码,而是为不正确的 ID 获取 500 状态代码
【发布时间】:2021-01-02 07:15:05
【问题描述】:

我是 Nodejs 的新手,我正在尝试使用 node js 来玩这些东西。

我创建了一个 api(使用 Nodejs、Express、Mongoose)来读取我试图在其中搜索无效用户 id(id 与 mongoDB 中的任何记录都不匹配)的用户。

404 响应永远不会触发。我输入了错误的 ID 并得到 500。

附上代码截图供参考:

enter image description here

【问题讨论】:

  • stackoverflow 问题中的代码需要粘贴为文本,而不是图像。请使用您问题下方的编辑链接来解决此问题。这是出于很多原因,例如可以搜索它,因此可以访问它,并且想要编写答案的人可以将代码复制/粘贴/修改为答案,而无需从头开始重新输入。请解决您的问题。

标签: node.js mongodb express mongoose


【解决方案1】:

对于使用 findById,您应该只将 id 作为单个值而不是在对象中传递。所以更新你的代码为

User.findById(_id) 

你很高兴

【讨论】:

    【解决方案2】:
    app.get('/useres/:id'), async (req, res) => {
    
        const _id = req.params.id;
        let user = await User.findById(_id).then((user) => {
            if (!user) {
                res.status(404).send()
            } else {
                res.status(200).json(user)
            }
        }).catch((e) => {
            res.status(500).send()
        })
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-12-06
      • 2011-07-07
      • 1970-01-01
      • 2019-07-22
      • 1970-01-01
      • 2013-02-27
      • 2016-10-24
      相关资源
      最近更新 更多