Empty req.body when doing http.post


#1

Hi,

I am using ionic2 and I am trying to do an http.post request to my nodejs express REST API. I can see the request is received, but I cannot get the request parameters. I double-checked I am using bodyParser, I checked req.body, req,query, req.params, but they are all empty. Any clue where I should look?

My code:
Ionic2:

var body = JSON.stringify({
    name: "My name",
    email: "myemail@email.com",
    id: "1092379817239821"
});
return this.http.post(URL, body).map(res => res.json());

Express server.js:
> var routes = require(’./modules/routes’);
> var bodyParser = require(‘body-parser’);
> app.use(bodyParser.json());
> app.use(bodyParser.urlencoded({
> extended: true
> }));
> app.use(’/’, routes);

routes.js:
var express = require(‘express’);
var router = express.Router();
router.post(’/create-user’, function(req, res) {

var name = req.body.name,
      email = req.body.email,
      id = req.body.id;

    //they are all empty

});


#2

Im having this similar issue… first of all, make sure you send the request with header

“Content-Type”: “application/x-www-form-urlencoded”

Then, here’s come the weird problem with express… you’re receiving empty value because if you console.log request.body you’ll find that the result came in the form of

{{key:value}:' '}

So, how do you handle this?

// check if the result reside in the key and try to parse the key, otherwise, handle the request as usual
try{req.body = JSON.parse(Object.keys(req.body)[0])}catch(err){req.body = req.body}


#3

Thanks symphony86, that was spot on. Adding the content-type header seems to have done the trick. It’s working now!