首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >bodyParser返回对象而不是字符串

bodyParser返回对象而不是字符串
EN

Stack Overflow用户
提问于 2022-10-28 07:11:27
回答 1查看 31关注 0票数 0

我试图在类型记录中使用express和body解析器来实现json内容侦听器,到目前为止,除了当我收到json web钩子时,控制台将它记录为一个对象而不是一个字符串,一切都很完美。

代码语言:javascript
复制
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();
});

它在控制台中返回以下内容

代码语言:javascript
复制
Server running on port 3000
Headers: [object Object]
Body: [object Object]

例如,如果我尝试按下面的方式记录数据,"status“键的值将被正确地解析和记录

代码语言:javascript
复制
console.log("Status: " + req.body.status);

知道为什么会发生这种事吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2022-10-28 07:24:36

使用JSON.stringify()将任何JSON或js对象(非循环)转换为字符串。

代码语言:javascript
复制
console.log(JSON.stringify(req.body))

因此,就你的情况而言,情况如下:

代码语言:javascript
复制
//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();
});
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/74231781

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档