如何在Express中的多个文件中包含路由处理程序? [英] How to include route handlers in multiple files in Express?
问题描述
在我的NodeJS express
应用程序我有 app.js
有几个常见的路由。然后在 wf.js
文件中,我想定义几条路线。
In my NodeJS express
application I have app.js
that has a few common routes. Then in a wf.js
file I would like to define a few more routes.
如何获取 app.js
来识别 wf中定义的其他路由处理程序。 js
文件?
How can I get app.js
to recognize other route handlers defined in wf.js
file?
一个简单的需求似乎不起作用。
A simple require does not seem to work.
推荐答案
如果要将路由放在单独的文件中,例如 routes.js
,您可以这样创建 routes.js
文件:
If you want to put the routes in a separate file, for example routes.js
, you can create the routes.js
file in this way:
module.exports = function(app){
app.get('/login', function(req, res){
res.render('login', {
title: 'Express Login'
});
});
//other routes..
}
然后您可以从 app.js
通过应用程序
对象 em>这样:
And then you can require it from app.js
passing the app
object in this way:
require('./routes')(app);
还可以看看这些例子
https://github.com/visionmedia / express / tree / master / examples / route-separation
这篇关于如何在Express中的多个文件中包含路由处理程序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!