发出包含JSON主体的POST请求时,request.body为空

时间:2013-02-16 09:28:40

标签: node.js mongodb express

我已经在这个问题上挣扎了几个小时,我觉得我已经坚持了下来。我正在做NodeJS,ExpressJS和MongoDB的教程。我在ExpressJS上构建了一个简单的API。

当发出包含JSON主体的cURL POST请求时,req.body为空,因此我看到错误。

特此提供一些资料/细节:

cURL请求:

curl -i http://localhost:3000/wines -X POST -H "Content-Type: application/json" -d "{'name': 'New Wine', 'year': '2009'}"

路线:

app.post('/wines', wines.addWine);

API方法:

exports.addWine = function (req, res) {
console.log('Req body' + req.body);
var wine = req.body;
console.log('Adding wine: ' + JSON.stringify(wine));

db.collection('wines', function (err, collection) {
    collection.insert(wine, {safe:true}, function (err, result) {
        if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            console.log('Success: ' + JSON.stringify(result[0]));
            res.send(result[0]);
        }
    });
});
}

抛出以下错误:

Listening on port 3000...
Connected to 'winedb' database
Req bodyundefined
Adding wine: undefined
TypeError: Cannot read property '_id' of undefined
    at insertAll (/home/ebsk/Documents/Dev/Node/nodecellar/node_modules/mongodb            /lib/mongodb/collection.js:291:39)
    at Collection.insert (/home/ebsk/Documents/Dev/Node/nodecellar/node_modules/mongodb    /lib/mongodb/collection.js:92:3)
    at exports.addWine (/home/ebsk/Documents/Dev/Node/nodecellar/routes/wines.js:56:20)

我期待着您的回复。提前感谢任何建议。

1 个答案:

答案 0 :(得分:4)

如果您遇到快递请求正文的问题,首先要检查的是应用程序是否配置为使用bodyParser,即:

app.use(express.bodyParser());

在这种特殊情况下,您可以查看您的实施是否与example匹配。

相关问题