NodeJs,Express,BodyParse和JSON
我试图使用Express 4.0实现一个简单的服务器,并与BodyParserparsing消息。 为了testing我的服务器,我使用邮差。
使用x-www-form-urlencoded
作为消息模式,它可以正常工作,但是使用JSON
更改消息我无法使用BodyParse
数据。
这是我的代码:
app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); var router = express.Router() router.get('/', function (req, res){ res.json({message: "nd..."}) }) var sendRoute = router.route('/msg') sendRoute.post(function(req, res){ // HERE IS THE PROBLEM****************************** // It works with urlencoded request but not with JSON var dataparam1 = req.body.param1 var dataparam2 = req.body.param2 **************************************************** . . . })
假设这是我从请求中获得的JSON数据:
[{"param1":"This is the param1", "param2":"This is the param2" }]
我的代码有什么问题? 我怎样才能得到JSON格式的参数?
如果您的请求正文是作为JSONstring发送的,那么您必须通过内容types标题告诉您的应用程序。
- 在Postman中,单击下拉列表旁边的
Headers
button以select方法和URL params
button。 (右上) - 一个表将展开,在左侧字段中填入
Content-Type
,在右侧字段中填入application/json
。 - 提交请求。
bodyParser
可以处理多种types的数据,但它必须知道您提交的格式。 它不会尝试猜测数据types。
在填充请求主体的textarea上方,下拉菜单(根据您的评论,此时设置为“JSON”)仅切换语法突出显示,但不会为您设置Content-Type标题。