简体   繁体   中英

Undefined Value For Response Body in Node.js in an Exports Function.

I have a controller accessed from a route through a

router.post('/human',human.create);

human is imported through its controller file which contains the following :

var config = require(__dirname + '/../config/config'),
logger = require(__dirname + '/../lib/logger'),
util = require(__dirname + '/../helpers/util');

exports.create = function(request, response, next){


response.send({

  id: "human_103tsG2eZvKYlo2CW5yEDyUe",
  firstName: "Patricia",
  middleName: null,
  lastName: "Cesar",
  sex: "Female",
  birthdate: null

});

};

Inside this create function, I can do

console.log(request);

And a humongous JSON object will apear in the terminal, including the attribute I need : body.

However, when I do, console.log(request.body) , it goes undefined.

Am I missing a particular functionality of Node or Express that needs to be coded out?

I guess you are using the express 4.x which decoupled lots of middleware packages, as @shredmill metioned, you should use

bodyParser = require ('body-parser')

...

app.use(bodyParser.json()); //i found this works for me comparing to use bodyParser()

req.body is not pre-parsed for you automatically. You should explicitly use the connect.json() middleware for this:

var connect = require('connect');
router.post('/human', connect.json(), human.create);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM