Node.js TypeError:无法读取null的'body'属性问题求助
解决TypeError: Cannot read properties of null (reading 'body')错误
问题核心
- 回调参数覆盖:
Post.findById的回调函数错误使用req、res作为参数名,直接覆盖了外层的请求/响应对象。内部的req实际是Mongoose回调的第一个参数(查询失败时为null或错误实例),而非原本的请求对象,因此读取req.body会触发Cannot read properties of null错误。 - 未定义变量:回调逻辑中使用的
post变量从未声明,正确的post应该是Post.findById回调的第二个参数(查询到的文档实例)。
修复后的代码
const Comment = require('../models/comments'); const Post = require('../models/posts'); module.exports.create = (req, res) =>{ console.log(req.body); // 修正回调参数,使用err接收错误,post接收查询结果 Post.findById(req.body.post, (err, post) => { // 处理Post查询错误 if (err) { console.log('查询Post失败:', err); return res.redirect('/'); } console.log(req.body.matter); if(post){ Comment.create({ matter: req.body.matter, post: req.body.post, user: req.user._id }, function(err, comment){ if(err){ console.log('添加评论到Post失败:', err); return; } post.comments.push(comment); post.save(); res.redirect('/'); }) } else { // 处理Post不存在的情况 console.log('目标Post不存在'); res.redirect('/'); } }) }
关键修改点
- 回调参数替换:将
(req, res)改为(err, post),遵循Mongoose回调的标准参数格式,同时避免覆盖外层的req、res对象。 - 完善错误处理:新增Post查询错误的判断逻辑,以及Comment创建失败的提示,避免静默失败。
- 补充边界处理:当查询不到对应Post时,添加提示并跳转,确保逻辑完整性。
内容的提问来源于stack exchange,提问作者Abhi bhutani
相关产品推荐
相关产品推荐

