Postman测试服务器Post请求报TypeError: Cannot read properties of undefined (reading 'name')
Post请求报错
TypeError: Cannot read properties of undefined (reading 'name') 解决方法 问题概况
- Get请求正常,Post请求触发报错:
TypeError: Cannot read properties of undefined (reading 'name') - 相关截图:
- VS Code中server.js文件:

- VS Code终端报错信息:

- Postman Post请求配置:

- 发送Post请求后的请求体:

- VS Code中server.js文件:
问题原因
从server.js代码截图可见,你直接尝试访问req.body.name,但没有配置Express的请求体解析中间件,导致req.body为undefined,读取name属性时触发类型错误。
解决方案
- 在你的server.js中添加JSON请求体解析中间件,必须放在路由定义之前:
const express = require('express'); const app = express(); // 关键:添加这行解析JSON格式请求体 app.use(express.json()); // 后续路由定义 app.post('/api/employees', (req, res) => { const newEmployee = { id: employees.length + 1, name: req.body.name, email: req.body.email }; employees.push(newEmployee); res.json(newEmployee); }); - 确认Postman请求体格式为
raw > JSON(从截图看已配置,确保JSON内容格式正确)
内容的提问来源于stack exchange,提问作者Mangala Karunarathne
相关产品推荐
相关产品推荐

