初学者的例子
我喜欢最初从@david-ellis 检查的内容,你应该深入研究它以理解它,因为它是一个很好的内容。然而,对于想要看到直接示例的初学者来说,我希望它更加简化。这就是我希望有人向我展示的内容。
让我们举一个典型的场景,您正在使用 Express,并且您的 app.js 文件中列出了很多路由。它的内容看起来像这样:
app.js
// ... startup code omitted above
app.get('/', function(req, res) {
res.render('index', { title : 'home' });
});
app.get('/contactus', function(req, res) {
res.render('contactus', { title : 'contact us' });
});
app.get('/anotherpage', function(req, res) {
res.render('anotherpage', { title : 'another page' });
});
// and so on...
您可以想象,如果您有 50 条路线,该文件可能会变得非常失控。如果能从 app.js 文件中删除一些混乱的内容,那就太好了。
您要做的就是在应用程序中创建一个“controllers”文件夹,这样您的结构现在看起来像这样:
app.js
/controllers
在“/controllers”中创建一个名为“index.js”的文件,然后放入以下代码。
/controllers/index.js
module.exports.set = function(app) {
// copy your routes listed in your app.js directly into here
}
从“app.js”文件中剪切并粘贴路线列表,并将其放入“/controllers/index.js”文件中。
在您的 app.js 文件中,删除您的路由并在其位置执行以下操作。
app.js
// remove your routes and replace with this code
var controllers = require('./controllers');
controllers.set(app);
现在,如果您想将“/controllers/index.js”文件也分开,让我们再添加一个示例,以便您可以了解 Node.js 在如何组织代码方面实际上就像俄罗斯娃娃一样。
在“/controllers”中添加一个文件“accounts.js”并将以下内容放入其中。
/controllers/account.js
module.exports.set = function(app) {
// put more app route listings here
}
现在在“/controllers/index.js”文件中,添加对“account.js”的引用
/controllers/index.js
var account = require('./account.js');
module.exports.set = function(app) {
// your routes here
// let "account.js" set other routes
account.set(app);
}
正如您可以想象的那样,您可以不断地将内容分解成越来越小的部分,并将更多文件夹放入文件夹中,并根据需要使用“require”进行引用。您可以对“/lib”或库文件使用相同的概念。 “node_modules”已经在这样做了。
这只是使用 Node.js 编程非常愉快的众多原因之一。
Manageable Express 4 路由示例
这是我回复的另一篇关于与此相关的 Express 4 路线的帖子。
使用 Express.js 嵌套路由器休息 https://stackoverflow.com/questions/25260818/rest-with-express-js-nested-router/30549313#30549313