我试图在类型记录中使用express和body解析器来实现json内容侦听器,到目前为止,除了当我收到json web钩子时,控制台将它记录为一个对象而不是一个字符串,一切都很完美。
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]例如,如果我尝试按下面的方式记录数据,"status“键的值将被正确地解析和记录
console.log("Status: " + req.body.status);知道为什么会发生这种事吗?
发布于 2022-10-28 07:24:36
使用JSON.stringify()将任何JSON或js对象(非循环)转换为字符串。
console.log(JSON.stringify(req.body))因此,就你的情况而言,情况如下:
//Create route (url that will be set as webhook url)
app.post('/webhook', (req, res, next) => {
console.log("Headers: " + JSON.stringify(req.headers));
console.log("Body: " + JSON.stringify(req.body));
next()
res.status(200).end();
});https://stackoverflow.com/questions/74231781
复制相似问题