I want to show success or error message depending upon the HTTP response status code that I will receiving upon sending my axios request ,using react-toastify (For example if the status code is 406 react-toastify should show a error message like "Some fields are empty" or if status code is "422" is should show a error message like "email already registered" and in case of status code "200" react-toastify should show a message "Account created successfully") on frontend.
Here is my backend api code
router.route('/register').post(upload.single('photo'), (req, res) => {
const name = req.body.name;
const email = req.body.email;
const phone = req.body.phone;
const work = req.body.work;
const password = req.body.password;
const cpassword = req.body.cpassword;
const photo = req.file.filename;
if(!name || !email || !phone || !work || !password || !cpassword || !photo ){
return res.status(406).json({message:"Some fields are missing"}) ;
}
User.findOne({email: email})
.then((userExist)=>{
if (userExist){
return res.status(422).json({Error:"Email already registered"});
}
const newUserData = {
name,
email,
phone,
work,
password,
cpassword,
photo
}
const newUser = new User(newUserData);
newUser.save().then(()=>{
res.status(201).json({message:"user created successfuly"});
alert("user created succcessfully")
}).catch((err)=>res.status(500).json({error:"registeration failed"})
);
}).catch((err)=>{console.log(err);});
});
Here is the function on front that fetch data from input field
const handleSubmit = (e) => {
e.preventDefault();
let url = 'http://localhost:3000/register'
const formData = new FormData();
formData.append('name', newUser.name);
formData.append('email', newUser.email);
formData.append('phone', newUser.phone);
formData.append('work', newUser.work);
formData.append('password', newUser.password);
formData.append('cpassword', newUser.cpassword);
formData.append('photo', newUser.photo);
axios.post(url , formData)
.then(res => {
console.log(res)
history.push('/login')
} )
.catch(err => {
console.log(err);
});
}