Express+body-parser接收Webhook时,req.body打印为对象而非字符串求助
我用TypeScript结合Express和body-parser实现JSON内容监听器,接收JSON Webhook时,控制台打印请求头和请求体显示[object Object],但单独访问req.body.status这类属性能正常获取值。
相关代码
import express from 'express'; import bodyParser from 'body-parser'; // Initialize express and define a port const app = express(); const PORT = 3000; // Start express on the defined port app.listen(PORT, () => console.log(`Server running on port ${PORT}`)); // Some rudimentary error handling app.use((err, req, res, next) => { console.log(err.stack); console.log(err.name); console.log(err.code); res.status(500).json({ message: 'Shit hit the fan hard' }); }); // Parse JSON app.use(bodyParser.json()); // Create route (url that will be set as webhook url) app.post('/webhook', (req, res, next) => { console.log("Headers: " + req.headers.toString()); console.log("Body: " + req.body.toString()); next(); res.status(200).end(); });
控制台输出
Server running on port 3000 Headers: [object Object] Body: [object Object]
原因
在JavaScript/TypeScript中,对象直接调用默认的toString()方法时,会返回[object Object]——这是Object.prototype.toString()的默认实现,仅用于标识对象类型,而非序列化对象的具体内容。
req.headers和req.body都是对象(body-parser已将JSON请求体解析为JS对象),当你用字符串拼接"Headers: " + req.headers.toString()时,会自动触发这个默认方法,因此输出[object Object]。
解决办法
有三种常用方式可以正确打印对象内容:
使用console.log多参数形式(推荐,控制台可展开对象)
直接把字符串和对象作为不同参数传入,Node.js会自动格式化输出:console.log("Headers:", req.headers); console.log("Body:", req.body);用JSON.stringify序列化对象
把对象转成带格式的JSON字符串,适合需要纯文本输出的场景:console.log("Headers: " + JSON.stringify(req.headers, null, 2)); console.log("Body: " + JSON.stringify(req.body, null, 2));其中
null为replacer参数(用于过滤属性),2为缩进空格数,让输出更易读。直接打印对象
不需要前缀字符串时,直接打印对象即可:console.log(req.headers); console.log(req.body);
额外提示
你的路由代码里,next()之后调用res.status(200).end()是无效的——next()会把请求控制权移交到下一个中间件/路由,后续的响应代码不会执行。如果不需要调用后续中间件,直接去掉next()即可。
内容的提问来源于stack exchange,提问作者Dimitar Georgiev

