Javascript BodyParser行为
我正在发送一个带有cURL的POST请求:Javascript BodyParser行为,javascript,json,node.js,curl,express,Javascript,Json,Node.js,Curl,Express,我正在发送一个带有cURL的POST请求: curl http://tarvos.local:8080/partial_Users/2 -d '{currentPage : 1, firstID : 53d62fc6642aecf45c8b456f }' 在我的NodeJS应用程序中,请求通过bodyParser.json()中间件。我有另一个处理请求的中间件: app.post('/partial_Users/:page', function(req, res, next) { v
curl http://tarvos.local:8080/partial_Users/2 -d '{currentPage : 1, firstID : 53d62fc6642aecf45c8b456f }'
在我的NodeJS应用程序中,请求通过bodyParser.json()中间件。我有另一个处理请求的中间件:
app.post('/partial_Users/:page', function(req, res, next) {
var destinationPage = req.params.page;
var currentPage = req.body.currentPage;
var firstID = req.body.firstID;
console.log(req.body)
console.log(''+ currentPage + firstID)
[...]
}
在这种情况下,我希望req.body.currentPage
返回1。事实上,它返回“undefined”
我注意到,当我执行console.log(req.body)时,会得到以下字符串:
{{currentPage:1,firstID:53d62fc6642aecf45c8b456f}:''}
现在很明显,req.body.currentPage
将返回undefined。出于某种原因,bodyParser没有正确解析JSON。对于req.body.firstID
,可以看到相同的行为
要么我没有正确使用BodyParser,要么我的JSON请求没有正确构造?您需要将
-H“Content-Type:application/JSON”
添加到您的curl命令行,否则假定application/x-www-form-urlencoded
。我猜BodyParser需要Content-Type:application/JSON
。