2012-01-27 73 views
28

使用最新的稳定node.js并从npm表达,我创建了我的第一个快速项目。正确的方式来组织myapp/routes/*

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

我立即假设我可以添加其他.js文件到路线/文件夹,它们将被包括在内。这并没有出现。只包含routes/index.js。将其他路线添加到routes/index.js工作正常。

根据快递项目生成器提供的结构,定义和组织快递路线的正确方法是什么?


答案,释义在DailyJS的文章:

鉴于以下途径:

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

...创建以下文件:

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

然后,在routes/index.js里面:

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

对于每组新的相关路由,请在routes /中创建一个新文件,并从routes/index.js中require()它。对不适合其他文件的路线使用main.js。

回答

18

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

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中的所有文件。每个路由设置如下:

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

要添加更多路由,您现在要做的就是将一个新文件添加到routePath目录。

+0

是你的'app.js'中的第一个代码块还是像'./route/index.js'? – 2015-05-20 15:55:47