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

使用Postman发送POST请求时遭遇Mongoose ValidationError问题求助

排查Postman POST请求的ValidationError问题

发送POST请求时收到错误提示:Error ValidationError: name: Path 'name' is required., tech: Path 'tech' is required.

问题原因分析

  • 中间件顺序错误:JSON解析中间件配置在路由注册之后,导致/app路由无法获取解析后的请求体,req.body为空,触发Mongoose必填字段验证失败。
  • express.json调用错误:app.use(express.json)缺少括号,未正确启用JSON解析功能。
  • (可选)Postman操作问题:未设置正确的请求头或参数格式,导致后端无法解析请求参数。

修复方案

1. 修正index.js的中间件配置

将解析中间件移至路由注册前,并修正express.json的调用方式:

const express = require('express')
const mongoose = require('mongoose')
const mongoDB  = 'mongodb://127.0.0.1:27017/local_library'
const routers = require('../public/app')

const bodyParser = require("body-parser")

const app = express()

// 先配置解析中间件,再注册路由
app.use(bodyParser.urlencoded({ extended: true }));
app.use(express.json()); // 修正调用方式,与bodyParser.json()功能重复,保留其一即可

// 注册路由
app.use('/app', routers)

mongoose.connect(mongoDB, { useNewUrlParser: true, useUnifiedTopology: true })
const con = mongoose.connection

con.on('open', () => {
    console.log('connected..')
})

app.listen(3000, () => {
    console.log('server started')
})

2. 检查Postman请求设置

  • 请求方法选POST,URL填写http://localhost:3000/app
  • 切换到Body标签,选择raw,格式选JSON
  • 输入符合格式的参数:
    {
        "name": "示例名称",
        "tech": "示例技术"
    }
    
  • 确保请求头包含Content-Type: application/json(选择raw JSON时Postman会自动添加)

验证修复

重启服务器后重新发送请求,即可正常保存数据并返回结果。

内容的提问来源于stack exchange,提问作者sumanth.js

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.16 18:35:27