Route configuration in NodeJS using Express 4.8

4

I am using v0.10.37 version of Node and 4.8 of Express. I'm trying to setup the route for the index. And the following errors appear

  

Error: Route.get () requires callback functions but got a [object Undefined]

Or:

  

Error: Can not find module './app/routes/home'

app / controller / home.js

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

        res.render('index', {nome: 'Express'});
    };

    return controller; 
};

app / routes / home.js

var controller = require('./app/controllers/home');
module.exports = function(app) {

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

};

config / express.js

var express = require('express');
var home = require('./app/routes/home');
module.exports = function() {
    var app = express();

    app.set('port', 3000);
    app.set('view engine', 'ejs');
    app.set('views', './app/views');
    //middleware

    home(app);

    return app;
};
    
asked by anonymous 11.10.2015 / 06:07

1 answer

3

You have some errors in your code.

Your first mistake does not seem to me related to the code you show in the question. Route.get() implies using the express router and I do not see this in your code.

There are two common ways to manage routes in a modular way in different files. One is with routes, such as in this question , the other is how you are using (with some errors that I will explain below).

app / controller / home.js

In this file you want to create and export the right controler object? and when the module is called it should return a property object, one of which index must be a function with parameters req , res and optional next .

In this case the syntax of this file should look like this:

var controller = {
    index: function(req, res) {
        res.render('index', {nome: 'Express'});
    }
};
module.exports = controller;

Problems finding files

In Node.js when you use require('./pasta/subpasta/ficheiro.js'); it always starts from the current directory. So ./ is for files in the same directory, ../ goes down a folder. So your path is wrong, I think you need require('../etc'); on the two you have, so first you have to get down the folder and then upload it.

So the complete code should be:

app / controller / home.js //

11.10.2015 / 08:44