request.body is empty when issuing POST requests containing JSON body
express, mongodb, node.js
Solution
If you ever have problems with a request body in express, the first thing you should check is if the application is configured to use `bodyParser`, i.e.:
app.use(express.bodyParser());
In this particular case you can check to see if your implementation matches the example.
Problem
I've struggling for few hours with this issue and I feel I'm stuck with it. I'm doing the tutorial of NodeJS, ExpressJS and MongoDB. I've built a simple API on ExpressJS. When issuing a cURL POST request containing a JSON body the req.body is empty and therefore I see an error. Hereby some source/details: The cURL request: ``` curl -i http://localhost:3000/wines -X POST -H "Content-Type: application/json" -d "{'name': 'New Wine', 'year': '2009'}" ``` The route: ``` app.post('/wines', wines.addWine); ``` The API method: ``` 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]); } }); }); } ``` The following error is thrown: ``` 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) ``` I'm looking forward to hearing from you. Thanks in advance for any suggestions.