小编典典

正确组织myapp / routes / *的方法

node.js

使用最新的稳定的node.js和npm的express,我创建了我的第一个express项目。

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

我立即假定我可以将其他.js文件添加到route /文件夹中,并且将它们包括在内。这没有成功。仅包含路由/index.js。向route /
index.js添加其他路由可以正常工作。

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


答案就是对DailyJS文章的解释:

给出以下路线:

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

…创建以下文件:

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

然后,在route / index.js内部:

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

对于每个新的相关路由组,在route /中创建一个新文件,并从route / index.js中对它进行require()。
将main.js用于实际上不适合其他文件的路由。


阅读 239

收藏
2020-07-07

共1个答案

小编典典

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

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目录中。

2020-07-07