What is the difference between node.js express route and controller?

Is there anything else or more powerful with a traditional express route controller?

If you have an express application and define models, will it become an MVC application or do you need more?

I'm just wondering if I have enough extra / simpler functions in my express node applications without upgrading to a more legitimate β€œcontroller”. If there is such a thing.

Thank!

Edit: clarify if you use this route:

// routes/index.js exports.module = function(req, res) { // Get info from models here, res.render('view', info: models); } 

How is it different from the controller? Is the controller capable of doing more?

+8
model-view-controller express
Oct 17 '12 at 21:18
source share
1 answer

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.

+10
Oct 18 '12 at 15:03
source share



All Articles