NodeJS:数据类型返回undefined

时间:2016-01-19 09:09:42

标签: angularjs node.js mongoose

这是我的controller.js

$scope.saveDetails = function(){
     if($scope.editMode == false){
    //$scope.hidesave = false;
    //$scope.person = "";
    console.log("i am in save")
    console.log($scope.person);
    $http.post('/details',$scope.person).success(function(response){
        console.log(response);
        refresh();
    })
    $state.go("itemList");

这是我的Route.JS

module.exports = function (app){
    console.log("Inside Routes");

    app.get('/details', require('./details/details').getDetails);   
    app.get('/details/:id', require('./details/details').getDetails_id);
    app.post('/details', require('./details/details').saveDetails);
    app.delete('/details/:id',require('./details/details').deleteDetails);
    app.post('/details/:id',require('./details/details').updateDetails);
};

这是我的详细信息。实际实现是:

exports.saveDetails = function (req, res) {
    console.log("Hi");
    console.log("this is to save: ",req.body);
    var person = new req.app.schema.detailsdb(req.body);
    person.save(req.body,function(err,docs){
        res.json(docs);
        console.log("docs: ",docs)
    });
};

当我尝试将数据从HTML页面插入数据库时​​,req.body返回undefined,我使用Mongoose编写了数据库

1 个答案:

答案 0 :(得分:0)

要解析JSON,您需要包含快速正文解析器模块并在路由之前使用它:

var bodyParser = require('body-parser')

// parse application/json
app.use(bodyParser.json())

// the rest of your routes here.

app.get('/details', require('./details/details').getDetails);   
app.get('/details/:id', require('./details/details').getDetails_id);
app.post('/details', require('./details/details').saveDetails);
app.delete('/details/:id',require('./details/details').deleteDetails);
app.post('/details/:id',require('./details/details').updateDetails);

https://github.com/expressjs/body-parser/blob/master/README.md