Monday, 17 August 2020

React/Node if/else statements not returning expected value on post request.

I have my React and Node servers running and I am trying to set up a sign up page. In my node server I have an error handler to check if all fields have something in them. In my react app I have a toast icon display the error message that is being sent from the server. My issue is my server is telling me one of my fields is empty even if they all have values in them. I have tested the route in postman and it works as expected this behavior only occurs when interacting with it from my React UI.Here is my rendering of the component and the fetch request I am making in React:const Signup = () => { const history = useHistory(); const [name, setName] = useState(""); const [password, setPassword] = useState(""); const [email, setEmail] = useState(""); const PostData = () => { fetch("/signup", { method: "post", header: { "Content-Type": "application/json", }, body: JSON.stringify({ name, password, email, }), }) .then((res) => res.json()) .then((data) => { if (data.error) { M.toast({ html: data.error, classes: "#c62828 red darken-3" }); } else { M.toast({ html: data.message, classes: "#43a047 green darken-1" }); history.push("/signin"); } }); }; return (

Finstagram

setName(e.target.value)} /> setEmail(e.target.value)} /> setPassword(e.target.value)} /> Alredy have an account
); }; export default Signup; In the postData function the logic I am having an issue with is at the bottom. For whatever reason data.error returns the first error message from this node function even when all fields are full:router.post("/signup", (req, res) => { const { name, email, password } = req.body; if (!email || !password || !name) { return res.status(422).json({ error: "please add all the fields" }); } User.findOne({ email: email }) .then((savedUser) => { if (savedUser) { return res .status(422) .json({ error: "user already exists with that email" }); } //encrypt password before placing in db bcrypt.hash(password, 12).then((hashedpassword) => { const user = new User({ email, password: hashedpassword, name, }); user .save() .then((user) => { res.json({ message: "saved succesfully" }); }) .catch((err) => { console.log(err); }); }); }) .catch((err) => { console.log(err); }); }); As you can see I get the status 422 and the message "please add all the fields." Any help is greatly appreciated.

Submitted August 17, 2020 at 08:05PM by TheSlothJesus

No comments:

Post a Comment