我正在使用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) {
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请求结构不正确?
答案 0 :(得分:2)
您需要将-H "Content-Type: application/json"
添加到curl命令行,否则会假定为application/x-www-form-urlencoded
。