Undefined Object

Asked

Viewed 434 times

3

I’m having problems with an object on Node.Js with Express.Js.

He 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.

Rota archive

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

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

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

Arquivo do Contrller

// 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 someone help me ?

1 answer

2


I think that defeniste the controller wrong way. How is export a function and not the object controller , hence the error.

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

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

where missing req and res, and where the external scope of the controller.

Do it like 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;

Browser other questions tagged

You are not signed in. Login or sign up in order to post.