gpt4 book ai didi

javascript - 使用 Express.JS 的基本 MVC 原则

转载 作者:太空宇宙 更新时间:2023-11-04 02:29:08 24 4
gpt4 key购买 nike

express.js为您提供了一个不错的准系统来实现标准的MVC开发模式。然而,我见过的大多数教程都在路由文件或全局应用程序文件中应用 Controller 逻辑。

在理想世界中:

模型 - 管理基本行为和数据

Controller - 向模型和 View 发送命令

View - 渲染模型中的数据

<小时/>

目前我有以下内容:

routes/index.js - 指向操作的路由

router.get('/hotels', function(req, res, next) {
hotels.run(req, res, next);
next();
});

controllers/hotels.js - Controller 向模型发送命令

module.exports = {
run: function(req, res, next) {
var users = new require('../models/hotels');
users.run(function(callback) {
res.render('hotels', { title: 'Hotels page', users: callback });
});
}
}

models/hotel.js - 模型请求数据

module.exports = {
run: function(callback) {
connection.query(sql, function(err, rows, fields) {
callback(rows);
//console.log(rows);
});
}
}

无论我尝试什么,我都无法从模型获取数据以返回到 Controller ,然后传递到 View 。我知道上述代码中可能存在多个错误,因为我是新来表达的。但基本原理应该没问题,我希望这对于我无法返回模型数据的原因是显而易见的,因为除了回调之外,上述所有逻辑都有效。

最佳答案

如果人们希望在 express.js 项目上使用类似的 MVC 方法,我相信我已经解决了这个问题。

routes.js - 进行了更改以匹配 Kevin 的更简洁的方法。

router.get('/hotels', hotels.run);

controller/hotels.js -

module.exports = {
run: function(req, res, next) {
var users = new require('../models/hotels');
users.run(function(err, callback) {
res.render('hotels', { title: 'Hotels page', users: callback });
});
}
}

models/hotel.js

module.exports = {
run: function(callback) {
connection.query(sql, function(err, rows, fields) {
callback(err, rows);
});
}
}

现在模型按照 Controller 的请求返回查询,使 Controller 能够将数据传递到 View 。

关于javascript - 使用 Express.JS 的基本 MVC 原则,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28371032/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com