我已經在這個問題上掙扎了好幾個小時,我覺得我一直堅持下去。我正在做NodeJS,ExpressJS和MongoDB的教程。我在ExpressJS上構建了一個簡單的API。當發出包含JSON主體的POST請求時,request.body是空的
當發出包含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)
我期待着您的迴音。在此先感謝您的任何建議。
如[在此](https://github.com/ccoenraets/nodecellar/blob/master/server.js)所示,您的服務器是否配置了'app.use(express.bodyParser())'? – 2013-02-16 10:02:08
非常感謝你的工作就像一個魅力! – ebsk 2013-02-16 10:43:07
@DavidWeldon您應該將其作爲答案發布。 – hexacyanide 2013-02-16 21:01:17