Node.js更新请求时req.body未定义,无法添加嵌套数组求助
问题解决:req.body未定义及数组嵌套更新错误
问题根源
express.json() 和 express.urlencoded({extended: true}) 仅能处理 application/json 和 application/x-www-form-urlencoded 格式的请求,无法解析 multipart/form-data,这就是你遇到 req.body 未定义的核心原因。
解决方案:使用multer处理multipart/form-data
1. 安装multer
npm install multer
2. 配置multer并挂载中间件
在你的Express项目入口文件(如app.js)中添加:
const multer = require('multer'); // 内存存储配置,适合仅传文本数据的场景;若需上传文件可调整存储路径 const upload = multer({ storage: multer.memoryStorage() });
3. 路由中使用multer中间件
给Update路由添加upload.none()中间件(无文件上传时使用):
// 示例路由,需根据实际路由路径调整 router.put('/podcasts/:id', upload.none(), Update);
修正Update函数中的其他问题
除了req.body的问题,你的代码还有几处逻辑错误需要调整:
updateOne的new: true参数无效,它不会返回更新后的文档;若要获取更新后的内容,建议使用findByIdAndUpdate。$push的写法错误,无需嵌套[{Episodes}],直接传入符合Schema的Episode对象即可。- 解构
const {Episodes} = req.body不符合Postman的传参结构,应直接从req.body中提取单个Episode的字段。
修正后的Update函数:
const Update = async (req, res) => { const _id = req.params.id; // 从req.body中提取单个Episode的字段,对应Postman中的传参 const newEpisode = { EpisodeNo: parseInt(req.body.EpisodeNo), EpisodeName: req.body.EpisodeName, EpisodeDescription: req.body.EpisodeDescription, imageurl: req.body.imageurl }; try { // 使用findByIdAndUpdate直接返回更新后的文档 const updatedPodcast = await Podcasts.findByIdAndUpdate( _id, { $push: { Episodes: newEpisode } }, { upsert: true, new: true } ); res.json(updatedPodcast); } catch (err) { res.status(500).json({ message: "Error in updating the data" }); console.error(err); } };
替代方案:改用application/json格式请求
如果不需要上传文件,可直接放弃multipart/form-data,改用application/json格式:
- Postman中选择
Body->raw->JSON - 传入符合结构的JSON数据:
{ "EpisodeNo": 1, "EpisodeName": "测试剧集", "EpisodeDescription": "测试描述", "imageurl": "测试链接" }
- 此时无需multer,
express.json()即可正常解析req.body,只需调整Update函数中参数获取逻辑即可。
内容的提问来源于stack exchange,提问作者FARHAN KHAN
相关产品推荐
相关产品推荐

