首先,express 中的路由是 connect 中定义的中间件。express 和其他框架的区别在于中间件大多位于控制器前面,控制器结束响应。express 使用中间件的另一个原因是 Node.js 的异步特性。
让我们看看控制器在 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');
});
});
};
关于这个 get 操作,您可能注意到的第一件事是嵌套的回调。这很难测试,很难阅读,如果你需要编辑你需要摆弄缩进的东西。因此,让我们通过使用流量控制来解决这个问题并使其平坦。
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.