Request.body is empty when issuing POST requests containing JSON body

I have been struggling for hours with this problem and I feel like I am stuck on this. I am doing the NodeJS, ExpressJS and MongoDB tutorial. I've built a simple API in ExpressJS.

When issuing a cURL POST request containing a JSON body, the req.body is empty and so I see an error.

Here are some sources / details:

CURL request:

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

      

Route:

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

      

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 am looking forward to hearing from you. Thanks in advance for any suggestions.

+3


source to share


1 answer


If you've ever had problems with the request body in express, the first thing you should check is that the app is configured to use bodyParser

, i.e .:

app.use(express.bodyParser());

      



In this particular case, you can check if your implementation matches.

+4


source







All Articles