ExpressJS中Postman POST请求body返回undefined问题求助
问题描述
在Windows 10服务器上使用Postman 11.0.12轻量版调用ExpressJS接口时,POST请求的JSON Body值始终返回undefined,但Query Params能正确获取对应值。尝试复制CURL代码在CMD窗口测试,仍出现相同问题。因环境限制无法使用Postman网页版或桌面版(暂无法在Win11上运行),怀疑是否遗漏了基础配置。
ExpressJS 代码
const sql = require('mssql'); const express = require('express'); const app = express(); const port = 5001; //SQL settings //-------------- // const config = { // user: bobbeat, // } //insert stock const postStock = `INSERT INTO [DEV].[dbo].[stocks] (code] ,[ID]) VALUES `; let resultRows = []; function queryDB(tableParam, stockID, addStockParams) { const sql = require("msnodesqlv8"); const connectionString = config; let tableToQuery = tableParam === : tableParam === 'postStock' ? postStock + '(' + addStockParams + ')' : 'No table found'; sql.query(connectionString, tableToQuery, (err, rows) => { rows ? console.log('rows returned') : console.log('errors are ', err) resultRows.push(rows); }); } app.get('/', (req, res) => { res.send('Hello World! from nodejs') }) //post stock app.post('/api/v1/postStock', (req, res) => { //cannot get whole body via req.body but query param works //1 //let stockBody = [ "req.body.code"]; console.log(req.query.code); //2 //post stock to db //queryDB('postStock', null, req.query.code); //return result res.send('resultRows'); }); //monitoring feature app.get('/running', (req, res) => { res.send('Api is up and PM2 monitoring'); }) app.listen(port, () => { console.log(`Example app listening on port ${port}`) })
Postman POST 请求(Raw JSON)测试结果
请求Body:
{ "code": "abc" }
控制台输出:
undefined
Query Params 测试结果
请求URL:
http://localhost:5001/api/v1/postStock?code=abc
控制台输出:
C:\BuildRunJSTools>node getSQLapi.js => type object Example app listening on port 5001 abc
解决方案
问题核心是Express默认不会自动解析JSON格式的请求体,导致req.body为undefined。只需添加JSON解析中间件即可解决:
在路由定义之前插入以下代码:
// 解析JSON格式的请求体 app.use(express.json());
如果需要同时支持URL编码的表单数据,可额外添加:
// 解析URL编码的请求体(可选) app.use(express.urlencoded({ extended: true }));
修改后的POST路由示例:
app.post('/api/v1/postStock', (req, res) => { // 现在可正常获取JSON Body中的值 console.log(req.body.code); res.send('resultRows'); });
配置完成后,Postman发送的JSON POST请求就能被正确解析,req.body.code可正常获取对应值。
内容的提问来源于stack exchange,提问作者Shucoder
相关产品推荐
相关产品推荐

