gpt4 book ai didi

mysql - 带 Node/express 和 mysql 的 mvc

转载 作者:行者123 更新时间:2023-11-29 05:52:01 24 4
gpt4 key购买 nike

我越来越糊涂了。我看到的所有关于 mySql 的教程最终都是这样的:

在模型/dbconnection.js 中

    var mysql = require('mysql');
port = process.env.PORT || 3333;

if (port == 3333) {
var connection = mysql.createConnection({
host: 'localhost',
port: 3306,
user: 'root',
password: 'root',
database: 'nameDataBase',
insecureAuth: true
});
} else {
console.log("Error");
}

connection.connect();
module.exports = connection;

然后在 routes/user.js 中

...    

router.delete("/:id", verifyToken, (req, res) => {
const newLocal = "DELETE FROM login_user WHERE id = ?";
connection.query(newLocal, [req.params.id], (err,rows,fields) => {
if (err) {
res.sendStatus(500);
return;
}
console.log(rows.affectedRows);
res.status(200).send({delete: rows});
});

});

module.exports = router;

模型和 Controller 在这里没有混合?如果明天我想更改数据库类型,我必须在模型和路由中进行更改。我不应该在 models/user.js 中创建诸如 getAllUsersBlaBla(params) 之类的函数,然后从 routes/user.js 调用它> ?

最佳答案

我同意。路由器中不应该有任何数据库查询,它被认为是 MVC 中 Controller 的一部分。

模型应该提供可以从 Controller 调用的数据库查询的包装函数。

许多 Node 应用程序(可能还有教程)会选择简单性而不是模块化,这就是为什么您会看到这样的代码。

关于mysql - 带 Node/express 和 mysql 的 mvc,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53142517/

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