Object Not Defined

3

I'm having trouble with an object in Node.Js with Express.Js.

It is reporting the following error.

Error: Route.get() requires callback functions but got a [object Undefined]
    at C:\contatooh\node_modules\express\lib\router\route.js:162:15
    at Array.forEach (native)
    at Route.(anonymous function) [as get] (C:\contatooh\node_modules\express\lib\router\route.js:158:15)
    at Function.app.(anonymous function) [as get] (C:\contatooh\node_modules\express\lib\application.js:421:19)
    at module.exports (C:\contatooh\app\routes\home.js:6:6)
    at module.exports (C:\contatooh\config\express.js:21:2)
    at Object.<anonymous> (C:\contatooh\server.js:5:38)
    at Module._compile (module.js:434:26)
    at Object.Module._extensions..js (module.js:452:10)
    at Module.load (module.js:355:32)

The code is apparently correct.

Route Archive

var controller = require('../controllers/home');

// app/routes/home.js
module.exports = function(app) {

    app.get('/index', controller.index );
    app.get('/', controller.index );
}

Contrller File

// app/controllers/home.js
module.exports = function() {
    var controller = {};
    controller.index = function(req, res){
        //retorna a página index.ejs
        res.render('index', {nome: 'Express'});
    };
    return controller;
}

Configuration File

var express = require('express');
var home = require('../app/routes/home');

module.exports = function(){
    var app = express();
    // Váriavel de Ambiente
    app.set('port', 3000);

    //middleware
    app.use(express.static('./public'));

    //Define qual view sera utilizada
    app.set('view engine', 'ejs');
    //Define onde novas views serão salvas
    app.set('views', '../app/views');

    home(app);
    return app;
}

Can anyone help me?

    
asked by anonymous 29.09.2015 / 05:51

1 answer

2

I think you've set controller wrong. Since you are exporting a function and not the object controller , hence the error.

When you did var controller = require('../controllers/home'); the variable controler would be:

function() {
    var controller = {};
    controller.index = function(req, res){

where req and res are missing, and where controller is not even reachable in outer scope.

Do this:

// app/controllers/home.js
var controller = {};
controller.index = function(req, res){
    // retorna a página index.ejs
    res.render('index', {nome: 'Express'});
}

module.exports = controller;
    
29.09.2015 / 09:01