MERN栈中向已有数组添加元素失败,请求技术帮助
问题排查与修复方案
1. 前端请求的Content-Type缺失 + 请求体格式错误
你的前端fetch请求未设置Content-Type头,且请求体直接传递了user.id的字符串,导致后端无法正确解析出req.body.follower。修改前端代码:
const handleFollow = async (e) => { const response = await fetch(`/api/user/follow/${params.userId}`, { method: 'POST', body: JSON.stringify({ follower: user.id }), // 改为对象格式匹配后端接收字段 headers: { 'Authorization': `Bearer ${user.token}`, 'Content-Type': 'application/json' // 新增该头,告知后端请求体为JSON格式 } }) }
2. 后端确保启用JSON解析中间件
在Express应用的主入口文件(如app.js)中,必须添加express.json()中间件,否则无法解析JSON格式的请求体,req.body会始终为undefined:
const express = require('express') const app = express() app.use(express.json()) // 必须添加这一行 // ...其他路由、中间件配置
3. 优化findOneAndUpdate参数逻辑
默认情况下findOneAndUpdate返回更新前的文档,且不会自动运行模型验证规则。修改后端代码,补充必要选项并完善参数校验:
const followUser = async (req, res) => { const { id } = req.params const { follower } = req.body // 先校验follower的合法性 if (!follower || !mongoose.Types.ObjectId.isValid(follower)) { return res.status(400).json({ error: 'Invalid follower ID' }) } if (!mongoose.Types.ObjectId.isValid(id)) { return res.status(404).json({ error: 'No such user' }) } // 添加new: true返回更新后的文档,runValidators确保模型验证生效 const user = await User.findOneAndUpdate( { _id: id }, { $push: { followers: follower } }, { new: true, runValidators: true } ) if (!user) { return res.status(404).json({ error: 'No such user' }) } res.status(200).json(user) }
额外调试建议
- 在后端
followUser函数开头打印req.body,确认是否正确接收follower值:console.log('Received request body:', req.body) - 检查User模型中
followers字段的定义,确保是数组类型:const userSchema = new mongoose.Schema({ // ...其他字段 followers: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }] })
内容的提问来源于stack exchange,提问作者PiWizard3852
相关产品推荐
相关产品推荐

