我正在使用Node js
和expressJs
创建一个REST API,但当我尝试创建用户时,突然遇到了一个问题,然后我可以这样创建它:
/**
* save user data from the user model
*/
router.post("/users", async (req, res) => {
const user = new User(req.body);
try {
await user.save();
res.status(201).send( user);
} catch (e) {
res.status(400).send(e);
}
});
创建用户后,我可以在poster中看到一个响应。
但当我尝试走/users/login
路线时,我遇到了一个问题,这表明400 bad requests
也无法得到任何响应。这是我的代码:
/**
* User login.
*/
router.post("/users/login", async (req, res) => {
try {
const user = await User.findByCredentials(
req.body.email,
req.body.password
);
res.send( user);
} catch (e) {
res.status(400).send();
}
});
/**
* user login crendentials
*/
userSchema.statics.findByCredentials = async (email, password) => {
const user = await User.findOne({ email });
if (!user) {
throw new Error("Unable to login");
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
throw new Error("Unable to login");
}
};
任何建议都将不胜感激谢谢
我通过返回user
解决了我的问题,如下所示:
/**
* user login crendentials
*/
userSchema.statics.findByCredentials = async (email, password) => {
const user = await User.findOne({ email });
if (!user) {
throw new Error("Unable to login");
}
const isMatch = await bcrypt.compare(password, user.password);
if (!isMatch) {
throw new Error("Unable to login");
}
return user; //-------->>>>>>> add this line
};