2013-02-16 30 views
3

我已經在這個問題上掙扎了好幾個小時,我覺得我一直堅持下去。我正在做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) 

我期待着您的迴音。在此先感謝您的任何建議。

+0

如[在此](https://github.com/ccoenraets/nodecellar/blob/master/server.js)所示,您的服務器是否配置了'app.use(express.bodyParser())'? – 2013-02-16 10:02:08

+0

非常感謝你的工作就像一個魅力! – ebsk 2013-02-16 10:43:07

+0

@DavidWeldon您應該將其作爲答案發布。 – hexacyanide 2013-02-16 21:01:17

回答

4

如果你有在明確請求主體的問題,您應該檢查的第一件事是如果應用程序配置爲使用bodyParser,即:

app.use(express.bodyParser()); 

你可以查看此特定情況下,如果您的實施符合example

+0

嘿@David Weldon,現在這個功能已經從express裏刪除了,express並沒有內置一個body parser。你需要安裝和使用第三方中間件來解析傳入請求的主體。 – buoyantair 2017-12-26 07:20:33

相關問題