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

MongoDB中req.body失效,req.body.Username未定义报错

问题解决:req.body.Username未定义导致服务器崩溃

核心原因

你没有在Express应用中配置请求体解析中间件,导致Express无法解析POST请求的消息体,req.body为空对象,自然获取不到Username字段。

解决步骤

  1. 添加请求体解析中间件
    在你的index.js文件开头、所有路由定义之前,添加以下代码:
const express = require('express');
const app = express();

// 解析JSON格式的请求体
app.use(express.json());
// 解析表单格式的请求体(可选,若需要支持表单提交)
app.use(express.urlencoded({ extended: true }));
  1. 优化代码(移除冗余的async/await与then/catch混用)
    原代码同时使用async/await和then/catch,写法冗余且易出错,建议统一用async/await + try/catch:
app.post('/users', async (req, res) => {
  try {
    // 检查用户是否已存在
    const existingUser = await Users.findOne({ Username: req.body.Username });
    if (existingUser) {
      return res.status(400).send(`${req.body.Username} already exists`);
    }
    // 创建新用户
    const newUser = await Users.create({
      Username: req.body.Username,
      Password: req.body.Password,
      Email: req.body.Email,
      Birthday: req.body.Birthday
    });
    res.status(201).json(newUser);
  } catch (error) {
    console.error(error);
    res.status(500).send(`Error: ${error.message}`);
  }
});
  1. Postman请求注意事项
    发送POST请求时,确保:
  • 切换到Body标签页
  • 选择raw格式,右侧下拉菜单选JSON
  • 输入符合格式的JSON数据示例:
{
  "Username": "testuser",
  "Password": "test123",
  "Email": "test@example.com",
  "Birthday": "1990-01-01"
}

补充说明

你之前用req.params.Username能正常工作,是因为params是从URL路径参数中提取数据,不需要解析请求体;而req.body是从请求的消息体中获取数据,必须依赖中间件完成解析。

内容的提问来源于stack exchange,提问作者Ben

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.16 12:07:10