我在这个问题上挣扎了几个小时,我觉得我被困住了。我正在做 NodeJS、ExpressJS 和 MongoDB 的教程。我在 ExpressJS 上构建了一个简单的 API。
发出包含 JSON 正文的 cURL POST 请求时,req.body 为空,因此我看到一个错误。
特此提供一些来源/详细信息:
卷曲请求:
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)
期待收到你的消息。在此先感谢您的任何建议。