简体   繁体   English

ZCCADCDEDB567ABAE643E15DCF0974E503Z findOne 总是返回 undefined

[英]Mongoose findOne always return undefined

When ever i tried to post this API via postman using email and password.每当我尝试使用 email 和密码通过 postman 发布此 API 时。

I get User Not Found .我得到用户未找到 I cross checked email and password 100+ times.我交叉检查了 email 和密码 100 多次。

In command prompt i am getting UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client.在命令提示符下,我收到UnhandledPromiseRejectionWarning: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client。

What i am doing wrong here.我在这里做错了什么。 Please tell me, Thank you in advance.请告诉我,提前谢谢你。

exports.loginUser = async (req, res) => {
    try{
      const user = await userTable.findOne({ email:req.body.email });
      if (!user){
        res.send({
          status: 404,
          message: "User Not Found"
        });
      }

      const hashpass = cryptr.decrypt(user.password);
      if (hashpass == req.body.password){

        const accessToken = jwt.sign({ id: user._id, email: user.email }, process.env.JWT_PASS, {expiresIn:"1d"});
        res.send({
          status: 200,
          data: user,
          jwt: accessToken
        });
      }else{
        res.send({
          status: 404,
          message: "Wrong password"
        });
      }
    }catch(err){
      res.status(500).send({
        status: 0,
        message: "catch issue" + err.message
      });
    };
};

Probably not answer to your question but can you replace your accessToken variable part with this code?可能无法回答您的问题,但您可以用此代码替换您的accessToken变量部分吗? I wrapped other side of the variable in a function and used await keyword for async purposes.我将变量的另一端包装在 function 中,并使用await关键字进行异步。 And please let me know if it helps, if it doesnt help, I will delete answer.如果有帮助,请告诉我,如果没有帮助,我将删除答案。

      const accessToken = await function() {
        jwt.sign(
          { id: user._id, email: user.email }, 
          process.env.JWT_PASS, 
          {expiresIn:"1d"});
      }

I'm pretty sure this is happening because your handler continues after sending a response, therefore attempting to modify a response after it's already been sent.我很确定这种情况正在发生,因为您的处理程序在发送响应后继续,因此在响应已经发送后尝试修改它。

Keep in mind, it could be how you are using the loginUser function.请记住,这可能是您使用loginUser function 的方式。 If you wouldn't mind updating your question showing us how you are using it, that would be super helpful!如果您不介意更新您的问题,向我们展示您是如何使用它的,那将非常有帮助!

There are a couple things that come to mind;我想到了几件事; 1. You may need to add a return statement somewhere, like on line 10/11 for example 2. You could also wrap the code after the first if statement inside an else statement to see if that changes things. 1. 您可能需要在某处添加 return 语句,例如在第 10/11 行 2. 您还可以将第一个if语句之后的代码包装在else语句中,看看是否会改变事情。

At the end of the day, I'm pretty sure your code is continuing after sending a response, which is why you see that error.归根结底,我很确定您的代码在发送响应后仍在继续,这就是您看到该错误的原因。

With returnreturn

exports.loginUser = async (req, res) => {
  try {
    let dataToSend = {};
    const user = await userTable.findOne({ email: req.body.email });
    if (!user) {
      res.send({
        status: 404,
        message: "User Not Found",
      });
      // Try adding this
      return;
    }
    const hashpass = cryptr.decrypt(user.password);
    if (hashpass == req.body.password) {
      const accessToken = jwt.sign({ id: user._id, email: user.email }, process.env.JWT_PASS, { expiresIn: "1d" });
      res.send({
        status: 200,
        data: user,
        jwt: accessToken,
      });
    } else {
      res.send({
        status: 404,
        message: "Wrong password",
      });
    }
  } catch (err) {
    res.status(500).send({
      status: 0,
      message: "catch issue" + err.message,
    });
  }
};

Wrap in else包裹在else

This is very ugly and should only be used to test in my opinion!这很丑陋,我认为只能用于测试!

exports.loginUser = async (req, res) => {
  try {
    const user = await userTable.findOne({ email: req.body.email });
    if (!user) {
      res.send({
        status: 404,
        message: "User Not Found",
      });
    } else {
      const hashpass = cryptr.decrypt(user.password);
      if (hashpass == req.body.password) {
        const accessToken = jwt.sign({ id: user._id, email: user.email }, process.env.JWT_PASS, { expiresIn: "1d" });
        res.send({
          status: 200,
          data: user,
          jwt: accessToken,
        });
      } else {
        res.send({
          status: 404,
          message: "Wrong password",
        });
      }
    }
  } catch (err) {
    res.status(500).send({
      status: 0,
      message: "catch issue" + err.message,
    });
  }
};

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM