You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Express.js报错:TypeError: Cannot read properties of undefined(req.body未定义)

解决Express中req.body未定义的问题

问题核心原因

你遇到的TypeError: Cannot read properties of undefined错误,由两个关键问题导致:

  1. Express默认不自动解析POST请求的表单数据,必须手动配置对应中间件;
  2. 表单提交地址与路由地址不匹配,请求没发到正确的处理逻辑上。

具体修复步骤

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.12 05:25:14