I have this onSubmit in my React script that gets called when I click the submit button:
const handleSubmit = (event) => { event.preventDefault(); const form = event.target; const rawdata = new FormData(form); const data = { email: rawdata.get('email'), password: rawdata.get('password'), }; console.log(data); const response = fetch('http://localhost:4000/register', { method: 'POST', headers: { 'Content-Type': 'application/json', }, body: JSON.stringify(data), }).then(response => { if(response.ok) { console.log('Form data sent successfully'); } else { console.error('Failed to send form data'); } }).catch (error => console.error(error)); }
It should send the data to my node js script and call the following function:
app.post("/register", function (req, res){ console.log("inside /register"); console.log("email: " + req.body.email); User.register({username: req.body.email}, req.body.password, function(err, user){ if(err) { console.log(err); console.log("couldn't register"); //res.redirect("/signup"); } else{ passport.authenticate("local")(req, res, function(){ console.log("login granted"); }); } }); });
But it says the data I'm trying to log (req.body.email) is undefined. If anyone can help me I would be very grateful. Thanks
I edited the code below and now I can get the data from my React script in my Node js script:
And in my node script I have to add the following line at the beginning:
it's OK now. The app.use line in node is the problem.