如何在 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?
一个简单的require似乎不起作用.
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
以这种方式传递 app
对象:
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屋!