组织myapp / routes / *的正确方法 [英] Proper way to organize myapp/routes/*

查看:143
本文介绍了组织myapp / routes / *的正确方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用最新的稳定的node.js并从npm表达,我创建了我的第一个快速项目。

Using latest stable node.js and express from npm, I've created my first express project.

默认生成的应用程序定义routes / index.js,包含渲染默认索引视图的单个路由。

The default generated app defines routes/index.js, which contains a single route that renders the default index view.

我立即认为我可以将其他.js文件添加到routes / folder,并将它们包含在内。这没有泛滥。只包含route / index.js。向route / index.js添加其他路由工作正常。

I immediately assumed I could add other .js files to the routes/ folder and they would be included. This didn't pan out. Only routes/index.js is ever included. Adding additional routes to routes/index.js works fine.

按照快速项目提供的结构,定义和组织Express路由的正确方法是什么生成器?

答案,在DailyJS中改写文章:

The answer, paraphrasing the article at DailyJS:

给出以下路由:

app.get('/', function() {});
app.get('/users', function() {});
app.get('/users/:id', function() {});

...创建以下文件:

... Create the following files:

routes/
├── index.js
├── main.js
└── users.js

然后,在route / index.js内:

Then, inside of routes/index.js:

require('./main');
require('./users');

对于每组新的相关路线,请在routes / )它来自routes / index.js。对于不适合其他文件的路由,请使用main.js。

For each new group of related routes, create a new file in routes/ and require() it from routes/index.js. Use main.js for routes that don't really fit in the other files.

推荐答案

我喜欢动态加载路由,而不是手动添加另一个需要每次添加一个新的路由文件。这是我目前使用的。

I prefer dynamically loading routes instead of having to manually add another require each time you add a new route file. Here is what I am currently using.

var fs = require('fs');

module.exports = function(app) {
    console.log('Loading routes from: ' + app.settings.routePath);
    fs.readdirSync(app.settings.routePath).forEach(function(file) {
        var route = app.settings.routePath + file.substr(0, file.indexOf('.'));
        console.log('Adding route:' + route);
        require(route)(app);
    });
}

当应用程序加载时,我调用它,然后需要在routePath中的所有文件。每个路线的设置如下:

I call this when the application loads, which then requires all files in the routePath. Each route is setup like the following:

module.exports = function(app) {
    app.get('/', function(req, res) {
        res.render('index', {
            title: 'Express'
        });
    });
}

要添加更多路线,您现在只需要添加一个新文件到routePath目录。

To add more routes, all you have to do now is add a new file to the routePath directory.

这篇关于组织myapp / routes / *的正确方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆