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

Express Todo API报Cannot read property 'text' of undefined错误求助

解决POST请求中Cannot read property 'text' of undefined的问题

这个错误的核心原因很明确:你的req.body是undefined,所以访问req.body.text才会抛出类型错误。这不是数据库或者模型的问题,而是Express没有配置解析JSON请求体的中间件。

问题分析

Express框架默认不会自动解析请求体中的JSON数据,当你用Postman发送JSON格式的POST请求时,请求体内容没有被解析,req.body自然就是undefined,导致你无法读取text属性。

解决方案

根据你使用的Express版本,有两种简单的修复方式:

方式1:使用Express 4.16+内置的JSON解析中间件

从Express 4.16.0开始,框架内置了express.json()中间件,无需额外安装包。只需要在你的路由代码之前添加这一行:

const express = require('express');
const app = express();

// 关键:添加JSON请求体解析中间件
app.use(express.json());

// 你的原有路由代码
app.post("/todos", (req, res) => { 
  var todo = new Todo({ text: req.body.text }) 
  todo.save().then((doc) => { 
    res.send(doc); 
  }, (e) => { 
    res.status(400).send(e); 
  }); 
}); 

app.get("/todos", (req, res) => { 
  Todo.find().then((todos) => { 
    res.send({todos}); 
  }, (e) => { 
    res.status(400).send(e); 
  }); 
}); 

app.listen(port, () => { 
  console.log(`Started on port ${port}`) 
}); 

module.exports = {app};

方式2:使用body-parser包(适用于旧版本Express)

如果你的Express版本低于4.16.0,需要手动安装body-parser包:

npm install body-parser --save

然后在代码中引入并使用:

const express = require('express');
const bodyParser = require('body-parser');
const app = express();

// 配置body-parser解析JSON请求体
app.use(bodyParser.json());

// 你的原有路由代码...

额外验证步骤

修复后,还要确认Postman的请求配置正确:

  • 请求头必须包含Content-Type: application/json
  • 请求体选择raw格式,并且类型设置为JSON,输入正确的JSON内容(比如{"text": "完成API测试"})

这样修改后,Express就能正确解析POST请求的JSON数据,req.body.text就能正常获取到值,你的Todo项应该就能成功创建了。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.15 08:50:34