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

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 server.js file
    • VS Code终端报错信息:Vs Code Terminal
    • Postman Post请求配置:Postman Post Request
    • 发送Post请求后的请求体:Postman body after sending the Post Request

问题原因

从server.js代码截图可见,你直接尝试访问req.body.name,但没有配置Express的请求体解析中间件,导致req.body为undefined,读取name属性时触发类型错误。

解决方案

  1. 在你的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);
    });
    
  2. 确认Postman请求体格式为raw > JSON(从截图看已配置,确保JSON内容格式正确)

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.24 19:18:18