React通过onSubmit向Node.js传值时req.body.email未定义问题求助
问题排查与解决方案
核心原因
Express 默认不会自动解析 JSON 格式的请求体,你的前端发送的是 JSON 数据,但后端未配置对应的解析中间件,导致 req.body 无法被正确解析,所以 req.body.email 为 undefined。
解决步骤
1. 在 Node.js 后端添加 JSON 解析中间件
在你的 Express 应用中,将 express.json() 中间件添加在所有路由定义之前:
const express = require('express'); const app = express(); // 新增:解析JSON格式的请求体,必须放在路由定义前 app.use(express.json()); // 原有的/register路由 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"); }); } }); });
2. 验证前端表单的 input 命名
确保前端表单中,邮箱和密码对应的 <input> 标签的 name 属性准确设置为 email 和 password,否则 FormData.get('email') 会获取到空值:
<form onSubmit={handleSubmit}> <input type="email" name="email" placeholder="邮箱" /> <input type="password" name="password" placeholder="密码" /> <button type="submit">提交</button> </form>
3. 确认请求数据正确性
可以在前端 fetch 请求前打印 data 对象,或者打开浏览器开发者工具的网络面板,查看请求的 Payload 内容,确认 JSON 数据是否正确发送到后端。
内容的提问来源于stack exchange,提问作者m0j1
相关产品推荐
相关产品推荐

