Node.js Express接口报错:JSON位置7处意外令牌/
接口调用异常排查求助
调用/add-following接口时,Postman返回错误:
{"success": false, "error": "Unexpected token / in JSON at position 7"}
异常现象
- 在
addFollowing函数开头打印userId和followId,终端无任何日志输出 - 已尝试用
json-sanitizer处理req.body,问题未解决 - 接口首次调用成功,后续所有调用均触发上述错误
相关代码
addFollowing 函数
const addFollowing = async (req, res, next) => { const userId = req.body.userId; const followId = req.body.followId; console.log(userId, followId); try { // Update the user's following list const updatedUser = await User.findByIdAndUpdate( userId, { $addToSet: { following: followId } }, { new: true } ).select("username email following followers"); if (!updatedUser) { return next(new ErrorResponse(404, "User not found")); } // Update the follower's followers list const updatedFollower = await User.findByIdAndUpdate( followId, { $addToSet: { followers: userId } }, { new: true } ).select("username email following followers"); if (!updatedFollower) { // Roll back the previous update to the user's following list await User.findByIdAndUpdate(userId, { $pull: { following: followId } }); return next(new ErrorResponse(404, "User not found")); } // Return the updated user and follower objects res.json({ user: updatedUser, follower: updatedFollower, }); } catch (err) { next(err); } };
路由配置
router.post("/add-following",protect, addFollowing);
排查方向建议
- 检查请求体合法性:JSON解析错误提示第7位出现
/,大概率是后续请求的Body格式异常。比如Postman里误加了//开头的注释、复制了带无效斜杠的内容,或者未将Content-Type设置为application/json。可以把请求Body复制到JSON校验工具里验证格式。 - 排查中间件问题:
protect中间件可能在处理后续请求时抛出异常,导致请求没走到addFollowing函数(所以无日志输出)。可以暂时注释protect中间件,测试后续调用是否正常,排除权限中间件的影响。 - 验证请求重复提交:首次成功后,后续是否重复发送了错误的请求?比如Postman历史请求里存了异常Body,或者前端缓存了错误参数。可以清空Postman历史,重新构造正确请求体测试。
- 添加前置日志:在路由最前面加全局中间件,打印请求的
Content-Type和原始req.body,确认请求到达服务器时的数据是否合法:
app.use('/add-following', (req, res, next) => { console.log('请求Content-Type:', req.get('Content-Type')); console.log('原始请求Body:', req.body); next(); });
- 检查数据库数据格式:首次调用成功后,数据库中用户的
following或followers字段是否存入了非ObjectId的异常数据?直接查询对应用户文档,确认字段格式是否正确。
内容的提问来源于stack exchange,提问作者chowacross
相关产品推荐
相关产品推荐

