Ad

How To Separate Router From Controller In Express App?

I want to separate routes from controller.

I tried this approach:

routes/index.js

var express              = require('express');
var router               = express.Router();
var wordMapperController = require('../controller/wordmapper');

router.get('/', wordMapperController());

module.exports = router;

controller/wordmapper.js

var __construct = function(req, res, next) {
    res.render('index', { title: 'Word Mapping for Sanskrit-Indonesian in BG' });

    next();
}

module.exports = __construct;

When I start the res is undefined, and prevent the app to be launched. How does I handle this? How is it app.use and handle router middleware being passed?

Ad

Answer

The reason why you're getting res is undefined is because you're calling the wordMapperController function and then passing what it returns (in this case undefined, since you don't return anything) as the callback to the router.get method...

This is what you should be doing instead:

routes/index.js

router.get('/', wordMapperController);

Also, there's no reason to call next() in your controller/wordmapper.js file...

From the express.js documentation:

If the current middleware function does not end the request-response cycle, it must call next() to pass control to the next middleware function. Otherwise, the request will be left hanging.

In your case, you're ending your request-response cycle with the res.render method invocation, therefore you should only be doing this:

controller/wordmapper.js

var __construct = function(req, res, next) {
    res.render('index', { 
        title: 'Word Mapping for Sanskrit-Indonesian in BG' 
    });
}
Ad
source: stackoverflow.com
Ad