我对快速服务器的 GET 请求收到 404 错误

问题描述 投票:0回答:2

我正在编写一个快速端点,以使用电子邮件从我的 mongoDB 数据库中获取用户凭据,但是当我用邮递员测试端点时,我收到了 404 错误,这是代码

/**GET: http://localhost:9000/api/user/[email protected] */ //url endpoint
export async function getUser(req, res){
const { email } = req.params;

 try {
    if(!email) return res.status(501).send({ error: "Invalid Username"})

    UserModel.findOne({ email }, function(err, user){
        if(err) return res.status(500).send({ err });
        if(!user) return res.status(501).send({ error: "Couldn't Find User"});

        return res.status(200).send(user)
    })
    
 } catch (error) {
    return res.status(404).send({ error: "Cannot find user data"})
 }
}

注:

  1. 电子邮件地址存在于我的 mongoDB atlas 中,我已经检查过了。
  2. 我在 postman 中使用 GET 方法

但是我的邮递员一直向我显示 404 错误“找不到用户数据”

我错过了什么?

node.js mongodb express http-status-code-404 get-request
2个回答
0
投票

我想您需要考虑使用百分比编码对电子邮件地址中的“@”符号进行编码,如下所示:

GET: http://localhost:9000/api/user/success123%40gmail.com

但是,我建议您将电子邮件作为正文参数而不是参数传递。


0
投票

mongoose
不再支持
findOne()
中的回调函数。您可以将数据保存在变量中或使用
.then()
,
.catch()
块。

这是您的代码解决方案的示例:

export async function getUser(req, res) {
  const { email } = req.params;
    
  try {
    if (!email)
      return res.status(501).json({ error: "Invalid Username" })
    
    await UserModel.findOne({ "email": email })
      .then((docs) => {
        return res.status(201).json(docs)
      })
      .catch((err) => {
        return res.status(501).json(err)
      });
  } catch (error) {
    return res.status(404).send({ error: "Cannot find user data" })
  }
}

这是您必须考虑的一些事情,

  1. 不要忘记在异步函数中使用
    await
    关键字。
  2. 尝试用 Ecmascript 编写代码
  3. findOne()
    中使用键值对。使用
    { "email": email }
    而不是
    { email }

希望对您有所帮助!

© www.soinside.com 2019 - 2024. All rights reserved.