使用Thunder Client调用Express接口时req.body.name未定义错误求助
解决Express无法获取Thunder Client发送的JSON请求体问题
你的核心问题是Express中间件顺序错误,express.json()没有在路由之前生效,导致请求体未被解析,req.body为空,所以req.body.name返回undefined。
修正步骤:
调整
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}`) });确认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
相关产品推荐
相关产品推荐

