我正在使用 Node 和 Mongoose 創建一個身份驗證系統。我在這里有一個登錄用戶功能:
export const loginUser = async (req, res) => {
try {
const email = req.body.email;
const password = req.body.password;
//const workingUser = await User.findById("xxxxxxxxxxxx");
console.log(await User.findByCredentials(email, password));
const user = await User.findbyCredentials(email, password);
console.log(user);
if (!user) {
return res.status(401).json({ error: "Login failed! Check authentication credentials." });
}
const token = await user.generateAuthToken();
res.status(201).json({ user, token });
} catch (error) {
res.status(400).json({ error: error });
}
};
我總是收到 400 錯誤。控制臺日志記錄“用戶”沒有顯示任何內容。當我用我的“findByCredentials”函式替換注釋掉的“findById”時,代碼運行良好。此外,在我控制臺日志“等待 User.findByCredentials(電子郵件,密碼)”的地方,我想要的用戶是控制臺記錄的,這讓我認為 findByCredentials 代碼已正確實作。
這是代碼:
// this method searches for a user by email and password
userSchema.statics.findByCredentials = async (email, password) => {
console.log(email);
const user = await User.findOne({ email });
if (!user) {
throw new Error({ error: "Invalid login details" });
}
const isPasswordMatch = await bcrypt.compare(password, user.password);
if (!isPasswordMatch) {
throw new Error({ error: "Invalid login details"});
}
return user;
}
const User = mongoose.model("User", userSchema);
export default User;
不完全確定我做錯了什么。謝謝
uj5u.com熱心網友回復:
您的代碼中有錯字(在第二行)
const user = await User.findByCredentials(email, password);
findByCredentials不是findbyCredentials。見首都B
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/431851.html
