Express + MongoDB 实现用户登录
使用 `User.findOne({ username })` 根据用户名查找用户,如果用户不存在,返回 404 错误。调用 `user.comparePassword(password)` 方法比较用户输入的密码和数据库中存储的加密密码,如果密码不匹配,返回 401 错误。
// 处理用户登录的路由
app.post("/login", async (req, res) => {
try {
const { username, password } = req.body;
// 根据用户名查找用户
const user = await User.findOne({ username });
if (!user) {
return res.status(404).json({ message: "User not found" });
}
// 比较密码
const isPasswordValid = await user.comparePassword(password);
if (!isPasswordValid) {
return res.status(401).json({ message: "Invalid password" });
}
// 生成 JWT
const token = jwt.sign(
{ userId: user._id, username: user.username },
secretKey,
{
expiresIn: "1h", // 令牌有效期为 1 小时,可根据需求调整
}
);
res.json({ message: "Login successful", token });
} catch (error) {
console.error("Error during login:", error);
res.status(500).json({ error: "Internal Server Error" });
}
});