I build a register page using React as Frontend, and Node Js as backend. However, when I try to check the delicate username. Axios from the Frontend doesn't show any error. I have written the catch in many different ways. But I still cannot find where the problem is. Could anyone help me out? Thanks!
Frontend
const handleSubmit = async (event) => {
event.preventDefault();
if (handleValidation()) {
await axios.post(registerRoute, {
username,
email,
password,
}).then((response) => {
console.log(response);
}).catch((error) => {
if (error.response.status === 11000) {
console.log(error.response.data);
}
})
navigate("/");
}
};
Backend
module.exports.register = async (req, res, next) => {
const { username, email, password } = req.body;
if (!username || typeof username !== 'string') {
return res.json({status: 'error', message: 'Invalid username'})
}
const usernameExit = await Users.findOne({username: username})
if (usernameExit) {
return res.status(11000).json({ message: "Username already exit" });
}
if (!password || typeof password !== 'string') {
return res.json({status: 'error', message: 'Invalid password'})
}
try {
const hashedPassword = await bcrypt.hash(password, 2);
const user = new Users({
username,
email,
password: hashedPassword,
});
user.save();
delete user.password;
return res.json({ status: true, user });
} catch (error) {
if (error.code === 11000) {
return res.status(11000).json({ message: "Username already exit" });
}
}
};