I'm creating a REST API using Node js and expressJs, but suddenly I have faced a problem when I tried to create a user then I can create it like this way:
/**
* 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);
}
});
after creating a user I can see a response in postman.
But When I tried to go /users/login routes then I have faced a problem it shows me 400 bad requests also can't get any response. here is my code:
/**
* 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");
}
};
Any suggestion will highly appreciated Thanks.
I have solved my problem by returning the user, like this way:
/**
* 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
};