Js + Express: 路由器 vs 控制器

对于 Node.js 和 Express,我是新手,我试图理解这两个看似重叠的概念,路由和控制器。

我看到过 simple 执行 app.js + 路由/* 的例子,这似乎足以路由所需的各种请求。

然而,我也看到人们谈论使用控制器,有些人暗示更正式的 MVC 模型(? ? ?)。

如果有人能帮我解开这个谜团,那就太好了,如果你有一个在 Node.js + Express 框架中设置控制器的好例子,那就太好了!

谢谢,

84145 次浏览

One of the cool things about Express (and Node in general) is it doesn't push a lot of opinions on you; one of the downsides is it doesn't push any opinions on you. Thus, you are free (and required!) to set up any such opinions (patterns) on your own.

In the case of Express, you can definitely use an MVC pattern, and a route handler can certainly serve the role of a controller if you so desire--but you have to set it up that way. A great example can be found in the Express examples folder, called mvc. If you look at lib/boot.js, you can see how they've set up the example to require each file in the controllers directory, and generate the Express routes on the fly depending on the name of the methods created on the controllers.

You can just have a routes folder or both. For example, some set routes/paths (ex. /user/:id) and connect them to Get, Post, Put/Update, Delete, etc. and then in the routes folder:

const subController = require('./../controllers/subController');


Router.use('/subs/:id');


Router
.route('subs/:id')
.get(subController.getSub)
.patch(subController.updateSub);

Then, in the controllers folder:

exports.getSub = (req, res, next) => {
req.params.id = req.users.id;
};

Just to make something. I've done projects with no controllers folder, and placed all the logic in one place.