Model view controller node.js express路由和控制器之间的区别是什么?
在快速路线上,传统控制器有什么不同或更强大的功能吗 如果您有一个express应用程序并定义模型,它是成为MVC应用程序,还是有更多必要 我只是想知道我是否因为没有升级到更合法的“控制器”而错过了node express应用程序中额外/更简单的功能。如果有这样的事 谢谢 编辑:为了澄清,如果您使用这样的路线:Model view controller node.js express路由和控制器之间的区别是什么?,model-view-controller,node.js,express,Model View Controller,Node.js,Express,在快速路线上,传统控制器有什么不同或更强大的功能吗 如果您有一个express应用程序并定义模型,它是成为MVC应用程序,还是有更多必要 我只是想知道我是否因为没有升级到更合法的“控制器”而错过了node express应用程序中额外/更简单的功能。如果有这样的事 谢谢 编辑:为了澄清,如果您使用这样的路线: // routes/index.js exports.module = function(req, res) { // Get info from models here, re
// routes/index.js
exports.module = function(req, res) {
// Get info from models here,
res.render('view', info: models);
}
它与控制器有什么不同?控制器能做更多的事情吗 首先,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');
});
}
在本例中,您可以提取堆栈的所有不同函数,并对它们进行测试,甚至可以将它们重新用于不同的路由。您可能已经注意到,控制流结构看起来很像中间件。因此,让我们在路径中用中间件替换堆栈
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');
}
);
因此,虽然在express.js中可能有控制器,但您可能会被迫使用流控制结构,这最终与中间件相同