我的 React 脚本中有这个 onSubmit,当我单击提交按钮时,它会被调用:
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)); }
它应该将数据发送到我的节点js脚本并调用以下函数:
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"); }); } }); });
但它说我尝试记录的数据(req.body.email)未定义。如果有人可以帮助我,我将不胜感激。谢谢
P粉3087835852024-04-03 09:16:55
我编辑了如下代码,现在我可以从我的 Node js 脚本中的 React 脚本获取数据了:
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); fetch('http://localhost:4000/register', { method: 'POST', headers:{ 'Content-Type' : 'application/json' }, body: JSON.stringify(data) }) .then(response => { console.log("response ok: " + response.ok); console.log("response status: " + response.status); console.log("response json: " + response.json()); if(response.ok) { console.log('Form data sent successfully'); return response.json(); } else { console.error('Failed to send form data'); } }).catch (error => console.error(error));
并且在我的节点脚本中,我必须在开头添加以下行:
app.use(bodyParser.json()); app.use(express.static("public")); app.set('view engine', 'ejs'); app.use(bodyParser.urlencoded({ extended: true }));
现在可以了。节点中的 app.use 行是问题所在。