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

前端 未结 1 2062
庸人自扰
庸人自扰 2021-02-13 01:10

Is there anything that is different or more powerful with a traditional controller over an express route?

If you have an express app and define models, does it become

1条回答
  •  情话喂你
    2021-02-13 01:20

    First of all a route in express is middleware as defined in connect. The difference between express and other frameworks is that middleware mostly sits in front of the controller and the controller ends the response. An other reason why express uses middleware is due to the nature of Node.js being asynchronous.

    Lets see what a controller might look 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 notice about this get action is the nested callbacks. This is hard to test, hard to read and if you need to edit stuff you need to fiddle with your indentation. So lets fix this by 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 different functions of the stack and test them or even re-use them for different routes. You might have noticed that the control flow structure looks a lot like middleware. So lets replace the stack with middleware in 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');
      }
    
    );
    

    So while it might technically be possible to have controllers in express.js you would probably be forced to use flow control structures, which in the end is the same as middleware.

    0 讨论(0)
提交回复
热议问题