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

使用Thunder Client调用Express接口时req.body.name未定义错误求助

解决Express无法获取Thunder Client发送的JSON请求体问题

你的核心问题是Express中间件顺序错误,express.json()没有在路由之前生效,导致请求体未被解析,req.body为空,所以req.body.name返回undefined。

修正步骤:

  1. 调整express.json()中间件的位置,将其移到挂载路由之前:
    修正后的index.js代码:

    const express = require('express');
    const app = express();
    const port = 4000;
    const mongoDB = require("./db");
    mongoDB();
    
    app.get('/', (req, res) => {
      res.send('Hello World!')
    });
    
    // 先解析JSON请求体,再挂载路由
    app.use(express.json());
    app.use('/api', require("./routes/CreateUser"));
    
    app.listen(port, () => {
      console.log(`Example app listening on port ${port}`)
    }); 
    
  2. 确认Thunder Client的请求配置无误:

    • 请求方法选择POST
    • 请求URL填写http://localhost:4000/api/createuser
    • Body标签页选择JSON格式,输入正确的请求体(示例):
      {
        "name": "test",
        "password": "123456",
        "email": "test@example.com",
        "location": "Beijing"
      }
      
    • Thunder Client选择JSON格式时会自动添加Content-Type: application/json请求头,无需手动设置

原理说明:

Express中间件按注册顺序执行,express.json()的作用是解析请求的JSON格式体,只有在路由之前注册,路由处理函数才能访问到解析后的req.body。你之前把它放在路由之后,路由执行时还没触发解析,所以req.body是undefined。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.17 08:52:49