[英]Undefined Value For Response Body in Node.js in an Exports Function.
我有一個通過路由訪問的控制器
router.post('/human',human.create);
人是通過其控制器文件導入的,該文件包含以下內容:
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
});
};
在此創建函數中,我可以執行
console.log(request);
一個巨大的JSON對象將出現在終端中,包括我需要的屬性:body。
但是,當我執行console.log(request.body)
,它變得不確定。
我是否缺少需要編碼的Node或Express的特定功能?
我猜您正在使用Express 4.x,它解耦了許多中間件軟件包,如@shredmill所提到的,您應該使用
bodyParser = require ('body-parser')
...
app.use(bodyParser.json()); //i found this works for me comparing to use bodyParser()
不會自動為您req.body
。 您應該為此明確使用connect.json()
中間件:
var connect = require('connect');
router.post('/human', connect.json(), human.create);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.