Express.js报错:TypeError: Cannot read properties of undefined(req.body未定义)
解决Express中req.body未定义的问题
问题核心原因
你遇到的TypeError: Cannot read properties of undefined错误,由两个关键问题导致:
- Express默认不自动解析POST请求的表单数据,必须手动配置对应中间件;
- 表单提交地址与路由地址不匹配,请求没发到正确的处理逻辑上。
具体修复步骤
1. 配置请求体解析中间件
在你的Express主入口文件(如app.js/server.js)中,添加以下代码,用于解析表单格式的请求数据:
const express = require('express'); const app = express(); // 解析application/x-www-form-urlencoded类型的表单数据 app.use(express.urlencoded({ extended: true }));
注意:中间件配置必须写在所有路由注册之前,否则路由无法获取解析后的
req.body。
2. 修正表单提交地址
你的路由处理的是/login路径,但表单的action属性写的是/register,导致请求未被正确路由处理。修改HTML表单代码:
<form action="/login" method="post"> <label for="username"></label> <input type="text" name="username" placeholder="Username" id="username" required> <label for="password"> <i class="fas fa-lock"></i> </label> <input type="password" name="password" placeholder="Password" id="password" required> <input type="submit" value="Login"> </form>
3. 验证修复结果
重启服务器后提交表单,控制台将正常打印username和password的值,不再抛出未定义错误。
额外提醒
如果后续需要处理JSON格式的请求体,可补充添加app.use(express.json());中间件,但当前表单提交场景只需配置urlencoded中间件即可。
内容的提问来源于stack exchange,提问作者GhostLucas
相关产品推荐
相关产品推荐

