First of all, the express route is middleware as defined in connect. The difference between express and other structures is that the middleware is mainly in front of the controller, and the controller completes the response. Another reason express uses middleware is because Node.js is asynchronous.
Let's see what the controller looks like in Javascript.
var Controller = function () { }; Controller.prototype.get = function (req, res) { find(req.param.id, function (product) { res.locals.product = product; find(res.session.user, function (user) { res.locals.user = user; res.render('product'); }); }); };
The first thing you probably noticed in this case is nested callbacks. This is difficult to verify, difficult to read, and if you need to edit material that you need to mess with your indentation. So fix it using flow control and make it flat.
var Controller = function () { }; Controller.prototype.update = function (req, res) { var stack = [ function (callback) { find(req.param.id, function (product) { res.locals.product = product; callback(); }); }, function (callback) { find(res.session.user, function (user) { res.locals.user = user; callback(); }); } ]; control_flow(stack, function (err, result) { res.render('product'); }); }
In this example, you can extract all the various functions of the stack and test them, or even reuse them for different routes. You may have noticed that the control flow structure is very similar to middleware. So let's replace the stack with middleware on our route.
app.get('/', function (req, res, next) { find(req.param.id, function (product) { res.locals.product = product; next(); }); }, function (req, res, next) { find(res.session.user, function (user) { res.locals.user = user; next(); }); }, function (req, res, next) { res.render('product'); } );
Thus, while it is technically possible to have controllers in express.js, you will probably have to use flow control structures that end up matching middleware.