BodyParser行为

时间:2014-07-29 15:40:21

标签: 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) {

    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请求结构不正确?

1 个答案:

答案 0 :(得分:2)

您需要将-H "Content-Type: application/json"添加到curl命令行,否则会假定为application/x-www-form-urlencoded