提交HTML表单后Express中req.body返回undefined求助
Express中提交HTML表单时req.body返回undefined的解决办法
你的问题核心是没有为Express配置表单数据解析中间件,Express默认不会自动解析POST请求的表单数据,导致req.body为undefined。
解决步骤如下:
添加表单解析中间件
在你的Express应用初始化代码中,所有路由定义之前添加以下代码(确保在app.post('/register', ...)之前执行):// 解析application/x-www-form-urlencoded格式的表单数据 app.use(express.urlencoded({ extended: true }));extended: true允许解析包含嵌套对象、数组的复杂表单数据;若只需简单键值对,可设为false,推荐保持true以支持更多场景。- 新版Express已内置该中间件,无需额外安装
body-parser包。
修正路由代码语法错误
你提供的路由代码末尾缺少闭合括号和分号,修正后如下:app.set('view engine', 'ejs'); app.post('/register', function(req, res) { console.dir(req.body, {depth:null}); console.log(req.body.username) console.log(req.body.email) console.log(req.body.password) }); // 补上闭合括号与分号补充表单字段(可选)
你的测试表单仅包含email字段,所以req.body.username和req.body.password仍会是undefined,若需要获取这两个值,需在表单中添加对应输入框:<form class="" action="/register" method="post"> <input type="text" name="username" placeholder="用户名"> <input type="text" name="email" placeholder="邮箱"> <input type="password" name="password" placeholder="密码"> <button type="submit" name="button">submit</button> </form>
配置完成后,重新启动应用提交表单,req.body就能正常获取到表单数据了。
内容的提问来源于stack exchange,提问作者unbaym
相关产品推荐
相关产品推荐

