我想实现一个简单的服务器使用Express 4.0和解析与BodyParser消息。要测试我的服务器,我使用Postman。NodeJs,Express,BodyParse和JSON
使用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格式的params?
当你发送JSON请求时,console.log(req.headers ['content-type'])'在你的POST路由中显示什么? – mscdex 2014-10-09 12:51:41
嗯......'text/plain; charset = UTF-8' – MatterGoal 2014-10-09 12:56:40
在postman中,我设置了raw和JSON。 – MatterGoal 2014-10-09 12:57:01