Express.js POST req.body is empty

So, I have the following code in my server.js file that I run with node.js. I use an expression to handle HTTP requests.

app.post('/api/destinations', function (req, res) { var new_destination = req.body; console.log(req.body); console.log(req.headers); db.Destination.create(new_destination, function(err, destination){ if (err){ res.send("Error: "+err); } res.json(destination); }); }); 

In the terminal, I run the following:

 curl -XPOST -H "Content-Type: application/json" -d '{"location": "New York","haveBeen": true,"rating": 4}' http://localhost:3000/api/destinations 

After starting server.js displays the following data.

 {} { host: 'localhost:3000', 'user-agent': 'curl/7.43.0', accept: '*/*', 'content-type': 'application/json', 'content-length': '53' } 

So req.body is {} . I read other stack overflow reports about similar issues when the content type was incorrect due to body-parser. But this is not a problem, because the content-type is application / json.

Any ideas on how to get the actual request body?

Thanks in advance.

+7
json javascript express body-parser
source share
2 answers

You also need bodyParser.json:

 app.use(bodyParser.urlencoded({ extended: true })); app.use(bodyParser.json()); 
+16
source share

Sometimes req.body shows {} if you forgot to put the name attribute in the input fields of the form. The following is an example:

 <input type="email" name="myemail" class="form-control" id="exampleInputEmail2" placeholder="Email address" required> 

Then req.body shows { myemail: ' mathewjohnxxxx@gmail.com ' }

I am posting this answer because I ran into a similar problem and it worked for me.

+5
source share

All Articles