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

Node.js报错TypeError: Cannot read property 'body' of undefined求助

解决TypeError: Cannot read property 'body' of undefined及相关问题

看起来你在Udacity项目里遇到了几个典型的Node.js/Express路由和异步代码的问题,我帮你一步步排查修复:

核心错误根源

你看到的TypeError: Cannot read property 'body' of undefined是因为在服务端的/addAnimal路由中,你错误地直接调用了addAnimal函数,而不是把它作为回调传递给post方法:

// 错误写法:立即执行了addAnimal,此时req/res都不存在
.post(addAnimal())

// 正确写法:传递函数引用,让Express在收到POST请求时再调用它
.post(addAnimal)

这个错误会导致addAnimal在服务器启动时就执行,此时没有请求上下文,req参数是undefined,自然无法读取req.body。

其他需要修复的问题

解决核心错误后,还有几个小问题会导致代码无法正常工作:

1. 变量名大小写不一致

在服务端的GET路由/all中,你定义的数组是animalData(小写开头),但在getData函数里却写成了AnimalData(大写开头),这会导致引用未定义的变量:

// 错误
function getData(req, res){
 res.send(AnimalData)
 console.log(AnimalData)
}

// 正确
function getData(req, res){
 res.send(animalData)
 console.log(animalData)
}

2. 重复发送HTTP响应

在addAnimal函数中,你连续调用了两次res.send(),这会触发Cannot set headers after they are sent to the client错误(一个请求只能发送一次响应)。修改成只发送一次响应:

function addAnimal(req, res){
 const newEntry = { // 建议添加const声明变量
 animal: req.body.animal,
 facts: req.body.fact,
 fav: req.body.fav
 }
 data.push(req.body);
 animalData.push(newEntry);
 console.log(animalData);
 res.status(200).send(animalData); // 只保留一个响应发送
};

3. 客户端代码的语法和逻辑错误

  • 对象语法错误:你传递给postData的参数写法不对,应该用大括号包裹对象,同时要确保从表单获取到animal和fact的值:
// 先获取表单输入值(假设你有对应的input元素id)
const animal = document.getElementById('animal').value;
const fact = document.getElementById('fact').value;
const fav = document.getElementById('fav').value;

// 正确的对象写法
let res = await postData('/addAnimal', {animal, fact, fav});
  • 重复return和错误的JSON解析:postData函数里有重复的return语句,而且newData已经是解析后的JSON对象,不需要再调用.json():
const postData = async ( url = '', data = {})=>{
 console.log(data);
 const response = await fetch(url, {
 method: 'POST',
 credentials: 'same-origin',
 headers: {
 'Content-Type': 'application/json',
 },
 body: JSON.stringify(data),
 });
 try {
 const newData = await response.json();
 console.log(newData);
 return newData; // 只返回一次解析后的数据
 }catch(error) {
 console.log("error", error);
 };
 };

4. 冗余的中间件

Express 4.16+已经内置了body-parser的功能,你可以去掉单独的body-parser依赖,用Express内置的中间件:

// 删掉这些
// const bodyParser = require('body-parser')
// app.use(bodyParser.urlencoded({ extended: true }));
// app.use(bodyParser.json());

// 保留Express内置的解析中间件
app.use(express.json());
app.use(express.urlencoded({ extended: true }));

把这些修改完后,重启你的Node.js服务器,应该就能正常处理POST请求并返回数据了。

内容的提问来源于stack exchange,提问作者Michael Wycklendt

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.06 12:59:05