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

向Mongoose提交数据时出现Cannot read properties of undefined (reading 'name')错误

解决方案:Mongoose提交数据时req.body.name未定义的问题

错误核心原因

Cannot read properties of undefined (reading 'name') 本质是req.body为undefined,导致无法读取其name属性。

具体修复步骤

  • 调整Express中间件顺序
    Express中间件按注册顺序执行,你当前先挂载路由再配置请求体解析中间件,会导致路由处理请求时请求体还未被解析。需将解析中间件移到路由挂载之前:

    const express = require("express");
    const app = express();
    const mongoose = require("mongoose");
    require("dotenv/config");
    const product = require("../backend/Router/productRoutes");
    
    // 先配置请求体解析中间件
    app.use(express.json());
    app.use(express.urlencoded({ extended: true }));
    
    // 再挂载路由
    app.use("/add", product);
    
    mongoose.connect(process.env.MONGO_DB, () => {
      console.log("DB CONNECTED");
    });
    
    app.listen(3500, () => {
      console.log("server up");
    });
    
  • 修复路由中的保存逻辑错误
    路由代码中创建了newItem实例,但错误调用了模型的save()方法,应调用实例的save():

    router.post("/", async (req, res) => {
      const newItem = new items({ name: req.body.name });
      try {
        const submitted = await newItem.save(); // 改为实例调用save
        console.log(submitted);
        res.status(200).json(submitted); // 新增响应,避免请求挂起
      } catch (err) {
        console.log(err);
        res.status(500).json({ error: err.message }); // 新增错误响应
      }
    });
    
  • 验证请求格式
    发送POST请求时,确保请求头Content-Type与发送的数据格式匹配:

    • 发送JSON数据时,设置Content-Type: application/json
    • 发送表单数据时,使用application/x-www-form-urlencoded格式

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.22 11:36:17