如何导出Express中的所有路线?
我有一个 NodeJS Express 应用程序,它在一个文件 (app.js) 中变得非常大。
我想将所有路由导出到一个外部文件中,例如 ./lib/routes.js
。怎么做呢?
如何导出以下代码并在主 app.js
中正确引用它?
app.get('/logout', function(req, res) {
res.render('logout', {
username: req.session.username
});
});
app.get('/dashboard', function(req, res) {
res.render('dashboard', {
username: req.session.username
});
});
app.get('/login', function(req, res) {
res.render('login', {
badLogin: false,
loginError: false
});
});
I have an NodeJS Express app that is getting really big in just one file (app.js).
I want to export all my routes into a single, external file, say ./lib/routes.js
. How to do that?
How to export the following bit of code and require it correctly in main app.js
?
app.get('/logout', function(req, res) {
res.render('logout', {
username: req.session.username
});
});
app.get('/dashboard', function(req, res) {
res.render('dashboard', {
username: req.session.username
});
});
app.get('/login', function(req, res) {
res.render('login', {
badLogin: false,
loginError: false
});
});
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
我所做的就是按控制器对我的路线进行分组。对于每组相关路由(用户、购物车等),我创建一个位于
app/controllers/foo.js
中的控制器文件,其中foo
是控制器名称。在我的主 javascript 服务器文件(当前所有代码都位于其中)中,我按名称require
每个控制器,然后调用其setup
函数,传入我的 Expressapp
对象,并允许控制器添加它需要的任何路由。在每个控制器内,我都会执行以下操作:
What I do is group my routes by controller. For each group of related routes (users, shopping cart, whatever), I make a controller file that lives in
app/controllers/foo.js
wherefoo
is the controller name. In my main javascript server file (where all your code currently lives), Irequire
each controller by name and then call itssetup
function, passing in my expressapp
object, and allow the controller to add whatever routes it needs.Inside each controller, I do something like:
为什么不做这样的事情:
另外,您可以轻松想象使用 http://nodejs。 org/docs/v0.4.8/api/fs.html#fs.readdir 循环遍历routes目录并以编程方式加载它们。
你甚至可以做一些类似的事情......
尽管我想我会花一点时间思考如何简化它。
Why not do something like this:
Also, you could imagine easily using http://nodejs.org/docs/v0.4.8/api/fs.html#fs.readdir to loop through a routes directory and load these up programmatically.
You could even do something along the lines of...
Though I think I'd spend a little time thinking about how to simplify that.
使用 glob 您可以导出目录中的所有路由,例如“/routes”:
然后
using glob you can export all routes on directory for example '/routes':
then