【问题标题】:Unable to find user with Mongoose.findOne()无法使用 Mongoose.findOne() 找到用户
【发布时间】:2022-11-28 00:47:13
【问题描述】:

我正在使用 fetch() 来调用一个 url,如下所示:

  const context = useContext(AuthContext);
  const navigate = useNavigate();

  const handleSubmit = (event) => {
    event.preventDefault();
    const data = new FormData(event.currentTarget);
    // console.log({
    // email: data.get("email"),
    // password: data.get("password"),
    // });
    if (data) {
      //TODO: Trigger a mutation or update
      fetch("http://localhost:4000/api/user/login", {
        method: "POST",
        crossDomain: true,
        headers: {
          "Content-Type": "application/json",
          "Accept": "application/json",
          "Access-Control-Allow-Origin": "http://localhost:4000",
        },
        body: JSON.stringify({
          email: data.get("email"),
          password: data.get("password"),
        }),
      })
        .then((res) => res.json())
        .then((result) => {
          console.log(result);
          if (result.token) {
            context.login(result);
            navigate("/Home");
          }
        })
        .catch((e) => console.log(e));
    } else {
      console.log("Login failed.");
    }
  };

{handleSubmit} 然后在点击页面上的提交按钮时触发。

登录控制器:

const login = async (req, res, next) => {
  function generateToken(user) {
    return jwt.sign(
      {
        id: user.id,
        email: user.email,
        username: user.username,
      },
      SECRET_KEY,
      { expiresIn: "1h" }
    );
  }

  const user = await User.findOne({ email });
  if (!user) {
    console.log("User not found.");
  }

  const match = bcrypt.compare(password, user.password);
  if (!match) {
    console.log("Wrong password.");
  }

  const token = generateToken(user);

  return { token };
};

现在抛出的错误是“找不到用户”。我不明白为什么没有找到用户,因为输入电子邮件地址的用户存在于我的 mongodb atlas 中。

请提供一些指导。干杯。

【问题讨论】:

  • 也许你需要const user = await User.findOne({ "email": email });
  • 哦,是的,那是我犯了一个错误。感谢那。我将其更改为 {"email": req.body.email}。错误消失了,但是当我点击提交时发生了第 n 次。没有错误,只是什么都没有。你知道这是为什么吗?

标签: javascript node.js reactjs mongodb express


【解决方案1】:

您需要在登录控制器中添加以下代码。

const {email} = req.body.email; 
const user = await User.findOne({ email });

从您的评论中我可以看出,当您提交表格时,您什么也得不到! 我可以看到您正在返回令牌。相反,如果一切顺利,您必须添加以下代码。

res.json({token: token})

或者

res.status(200).json({token})

如果一切正常,那么您将收到如下响应:

{
 token: "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiIxMjM0NTY3ODkwIiwibmFtZSI6IkpvaG4gRG9lIiwiaWF0IjoxNTE2MjM5MDIyfQ.SflKxwRJSMeKKF2QT4fwpMeJf36POk6yJV_adQssw5c"
}

还有一件事要处理

if(!user) {
  //here you should use either of the following line 
  //next('No such user found')
  res.status(404).send('No user found with that email')
}
 if (!match) {
    //here you should use either of the following line 
  //next('Password Mismatch')
  res.status(400).send('Password Mismatch')
  }

这是为什么 ? 因为如果您不处理此类错误,您的应用将不会响应! 因为它会卡在中间件生命周期中!

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-02
    • 1970-01-01
    • 2016-04-14
    • 1970-01-01
    • 2017-02-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多