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

Node.js接收Postman对象数组请求时req.body为undefined的解决办法

问题描述

我创建了一个包含对象数组属性的Mongoose Schema,用Postman发送带对象数组的请求时,Node.js服务器读取到的req.body是undefined。试过修改MongoDB数组的创建方式,问题还是没解决。

Postman请求示例

{
    "waiter": "Pinoscotto",
    "to prepare": [{"element": "Pizza margherita", "amount": 1}]
}

Mongoose Schema定义

const orderSchema = new mongoose.Schema({
      _id: {type: String},
      n_table: {type: Number, required: true},
      waiter: {type: String, required: true},
      cook: {type: String},
      to_prepare: [{element: String, amount: Number}]
})
解决方案
  • 先确认服务器是否配置了JSON请求体解析中间件
    Node.js不会自动解析JSON格式的请求体,如果你用Express框架,必须在路由定义前添加以下中间件:

    const express = require('express');
    const app = express();
    
    // 关键:添加这行解析JSON请求体
    app.use(express.json());
    

    要是用的旧版Express,可能需要依赖body-parser包:

    const bodyParser = require('body-parser');
    app.use(bodyParser.json());
    
  • 修正请求字段与Schema字段的匹配问题
    请求里的"to prepare"带空格,但Schema里对应的字段是to_prepare(下划线命名),不仅会导致数据无法正确映射到Schema,还可能间接引发解析问题。把请求字段改成和Schema一致:

    {
        "waiter": "Pinoscotto",
        "to_prepare": [{"element": "Pizza margherita", "amount": 1}],
        "n_table": 1 // 注意Schema里n_table是必填项,请求必须包含该字段
    }
    
  • 检查Postman的请求头配置
    确保Postman的请求头里设置了Content-Type: application/json,如果没设置,服务器无法识别请求体格式,也会导致req.body返回undefined。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.14 23:47:26