【发布时间】: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