[英]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. 一个巨大的JSON对象将出现在终端中,包括我需要的属性:body。
However, when I do, console.log(request.body)
, it goes undefined. 但是,当我执行
console.log(request.body)
,它变得不确定。
Am I missing a particular functionality of Node or Express that needs to be coded out? 我是否缺少需要编码的Node或Express的特定功能?
I guess you are using the express 4.x which decoupled lots of middleware packages, as @shredmill metioned, you should use 我猜您正在使用Express 4.x,它解耦了许多中间件软件包,如@shredmill所提到的,您应该使用
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. 不会自动为您
req.body
。 You should explicitly use the connect.json()
middleware for this: 您应该为此明确使用
connect.json()
中间件:
var connect = require('connect');
router.post('/human', connect.json(), human.create);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.