Node.js错误:Route.get()需要回调函数但得到[对象未定义]

时间:2016-06-07 23:33:50

标签: javascript node.js express

您好我知道这个问题在stackoverflow中很常见,但我通过了所有这些问题,我真的无法解决我的代码有什么问题。

这是我的主要server.js



var dbUri =  process.env.MONGODB_URI;
var app = express();
var PORT = process.env.PORT || 3001;
var bodyParser = require('body-parser');
var mongoose = require('mongoose');


app.use(express.static(path.join(__dirname, 'public')));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
  extended: true
}));

if (app.settings.env === 'development') {
    dbUri = 'mongodb://localhost/barsDb';
}

mongoose.connect(dbUri, function (err, res) {
    if (err) {
        console.log('Erorr connection to database ' + dbUri + '.' + err);
    } else {
        console.log('Connected to database on ' + dbUri + "\n");
    }
});

//app.use(require('./routes.bars'));
require('./routes.bars')(app); //error here reciving undefined


// connect to server
app.listen(PORT, function () {
    console.log('Listening to port ' + PORT + '...');
});




这些是我的routes.js



var bars = require('./controllers/controller.bar');
var mongoose = require('mongoose');


module.exports = function(app) {
	app.route('/').get(bars.getMain);  //error in this line it is returning undefinded.
	app.route('/bars').get(bars.getBars);
	app.route('/bars').post(bars.addBar);
	app.route('/bars/:id').put(bars.updateBarById);
	app.route('/bars/:loc').get(bars.getByLocation);
	app.route('/bars/:id').get(bars.getBarById);
	app.route('/bars/:id').delete(bars.deletBarById);
};




这是我的控制者:



var mongoose = require('mongoose');
var dbModel = require('./../model/bars.db');
var path = require('path');
var _ = require('underscore');


// main page
module.getMain = function (req, res) {
   res.sendFile(path.join(__dirname + "/../public/index.html"));
};

// post new bar
module.addBar = function (req, res) {
    var body = _.pick(req.body,'name', 'address', 'phone', 'barType', 'ambient', 'options', 'loc');
    console.log(body);
    var newBar = new dbModel(body);

    newBar.save(function (err) {
        if (err) throw err;
        //res.send('Bar Created');
        res.status(201).send();
    });
};

// get all bars
module.getBars = function (req, res) {
    dbModel.find({},function (err, bars) {
        if (err) throw err;
        res.json(bars);
        //res.status(200).send();
    });
};

//get bars by location
module.getByLocation = function (req, res) {
    var barLoc = req.params.loc.split(",");
    var barLocLon = parseFloat(barLoc[0]);//.toFixed(5);
    var barLocLat = parseFloat(barLoc[1]);//.toFixed(5);
    barLoc = [];  barLoc.push(barLocLon);  barLoc.push(barLocLat);

    dbModel.find({
        loc:  {$gt:[barLocLon - 0.0200, barLocLat - 0.0200], $lt:[barLocLon + 0.0200, barLocLat + 0.0200]}
    }, function (err, bars) {
        if (err) throw err;
        res.json(bars);
        res.status(200).send();
    });
};

// get bar by id:
module.getBarbyId = function (req, res) {
    var barId = req.params.id;
    dbModel.findById(barId, function (err, bar) {
        if (err) throw err;
        res.json(bar);
        res.status(200).send();
    });
};

// update bar by id:
module.updateBarById = function (req, res) {
    var barId = req.params.id;
    var body =  _.pick(req.body,'name', 'address', 'phone', 'barType', 'ambient', 'options', 'loc');
    dbModel.findById(barId, function (err, bar) {
        if (bar) {

            bar.save(function (err) {
                if (err) throw err;
            });
        }
    });
    dbModel.findByIdAndUpdate(barId, {$set:req.body}, function (err, bar) {
        if (err) throw err;
        res.send('Updated');
    });
};

// delete bar by id:
module.deleteBarById = function (req, res) {
    var barId = req.params.id;
    //console.log(barId);
    dbModel.findByIdAndRemove(barId, function (err) {
        if (err) throw  err;
        res.send('Deleted id ' + barId);
    });
};




1 个答案:

答案 0 :(得分:0)

像这样包裹你的功能。

var myFunctions = {
    // get bar by id:
    getBarbyId: function (req, res) {
        var barId = req.params.id;
        dbModel.findById(barId, function (err, bar) {
            if (err) throw err;
            res.json(bar);
            res.status(200).send();
        });
    },

    // update bar by id:
    updateBarById: function (req, res) {
        var barId = req.params.id;
        var body = _.pick(req.body, 'name', 'address', 'phone', 'barType', 'ambient', 'options', 'loc');
        dbModel.findById(barId, function (err, bar) {
            if (bar) {

                bar.save(function (err) {
                    if (err) throw err;
                });
            }
        });
        dbModel.findByIdAndUpdate(barId, {
            $set: req.body
        }, function (err, bar) {
            if (err) throw err;
            res.send('Updated');
        });
    },

    // delete bar by id:
    deleteBarById: function (req, res) {
        var barId = req.params.id;
        //console.log(barId);
        dbModel.findByIdAndRemove(barId, function (err) {
            if (err) throw err;
            res.send('Deleted id ' + barId);
        });
    }
}

module.exports = myFunctions;

现在你可以使用你的"控制器"像这样:

var myControllerFuncs = require('path/controller.js');

//myControllerFuncs.updateBarById...