我是nodeJS和expressJS的新手,目前从expressJS获得以下错误:
TypeError: Cannot read property 'name' of undefined
at C:\Users\jitheshlive\IdeaProjects\nodejs-express-start\server.js:37:31
at callbacks (C:\Users\jitheshlive\IdeaProjects\nodejs-express-start\node_modules\express\lib\router\index.js:161:37)
at param (C:\Users\jitheshlive\IdeaProjects\nodejs-express-start\node_modules\express\lib\router\index.js:135:11)
at pass (C:\Users\jitheshlive\IdeaProjects\nodejs-express-start\node_modules\express\lib\router\index.js:142:5)
at Router._dispatch (C:\Users\jitheshlive\IdeaProjects\nodejs-express-start\node_modules\express\lib\router\index.js:170:5)
at Object.router (C:\Users\jitheshlive\IdeaProjects\nodejs-express-start\node_modules\express\lib\router\index.js:33:10)
at next (C:\Users\jitheshlive\IdeaProjects\nodejs-express-start\node_modules\express\node_modules\connect\lib\proto.js:199:15)
at C:\Users\jitheshlive\IdeaProjects\nodejs-express-start\node_modules\body-parser\lib\read.js:107:5
at IncomingMessage.onEnd (C:\Users\jitheshlive\IdeaProjects\nodejs-express-start\node_modules\body-parser\node_modules\raw-body\index.js:136:7)
at IncomingMessage.g (events.js:260:16)
我的expressJS代码如下:
app.configure(function(){
app.use(express.logger());
app.use(express.static(__dirname + '/app'));
app.use(bodyParser.json());
app.engine('html',engines.underscore);
/*
Set views direcoctory. DO NOT set this with the static directory!.
*/
app.set('views', __dirname+'/app/views');
app.set('view engine', 'html');
app.set('PORT',config.server.port);
});
app.get("/", function(req,res){
res.render('index');
});
app.post("/webservice-1.0/rest/student/add/", function(req,res){
console.log(req.param.student.name);
console.log(req.param.student.address);
//res.render('index');
});
我在UI中使用angularJS来提交数据。我的angularJS控制器如下:
mainApp.controller("addStudentController", function($scope,$http) {
var resData = {};
$scope.output = "";
var url = "/webservice-1.0/rest/student/add/";
$scope.addStudent = function(){
$http.post(url, $scope.student)
.success(function(data, status, headers, config) {
resData = angular.fromJson(data);
$scope.output = "Student entered successfully with unique Id "+resData.id;
}).error(function(data, status, headers, config) {
resStatus = status;
$scope.output = "Something went wrong. Please try again later."
});
}
});
答案 0 :(得分:0)
这意味着没有req.param.student.name
。要查看从客户端到服务器端的内容,只需执行以下操作:
console.log(req.body)
您正在使用请求正文发送数据,而非params。
然后req.body.data.name
或req.body.data.student.name
之类的内容就可以了。