Express API调试:控制台打印req.body显示[object Object]的解决需求
解决方案
问题原因
直接拼接req.body(对象类型)与字符串时,JavaScript会自动调用对象的toString()方法,默认返回[object Object],这就是你看到输出的原因。
1. 输出格式化的请求对象(JSON字符串)
如果只是想把解析后的请求体以可读的字符串形式输出,使用JSON.stringify()即可,第二个参数null和第三个参数2用于格式化缩进:
function test1(req: Request, res: Response, next: NextFunction): string { // 格式化输出JSON字符串 console.log("Request==>" + JSON.stringify(req.body, null, 2)); let respuestaJSON: string = ""; return respuestaJSON; }
2. 获取Postman发送的原始XML请求内容
从你的请求截图来看,Postman发送的是XML格式的请求。如果需要获取未解析的原始XML字符串,需要先在Express中添加中间件捕获原始请求体:
步骤1:添加捕获原始请求体的中间件
在所有解析中间件(比如XML/JSON解析)之前添加:
// 扩展Request类型,避免类型报错(可选) declare global { namespace Express { interface Request { rawBody?: string; } } } // 捕获原始请求体 app.use((req, res, next) => { let rawBody = ''; req.on('data', (chunk) => { rawBody += chunk.toString(); }); req.on('end', () => { req.rawBody = rawBody; next(); }); });
步骤2:配置XML解析中间件(如果需要解析XML为对象)
安装express-xml-bodyparser依赖后配置:
npm install express-xml-bodyparser
import xmlParser from 'express-xml-bodyparser'; app.use(xmlParser());
步骤3:在函数中输出原始XML
function test1(req: Request, res: Response, next: NextFunction): string { // 输出原始XML请求内容 console.log("Raw Request XML==>" + req.rawBody); let respuestaJSON: string = ""; return respuestaJSON; }
3. 将解析后的请求对象转为XML字符串
如果已经将XML解析为对象,想再转回XML格式输出,可以使用json2xml库:
npm install json2xml
import json2xml from 'json2xml'; function test1(req: Request, res: Response, next: NextFunction): string { // 将请求对象转为XML字符串 const xmlString = json2xml(req.body); console.log("Request XML==>" + xmlString); let respuestaJSON: string = ""; return respuestaJSON; }
内容的提问来源于stack exchange,提问作者Javi
相关产品推荐
相关产品推荐

