如何在Express中的多个文件中包含路由处理程序?

在我的NodeJS express应用程序中,我有app.js一些常见的路由。然后在一个wf.js文件中我想定义更多的路线。


如何app.js识别wf.js文件中定义的其他路由处理程序?


一个简单的要求似乎不起作用。


波斯汪
浏览 943回答 3
3回答

莫回无

在@ShadowCloud的例子的基础上,我能够动态地包含子目录中的所有路由。路线/ index.jsvar fs = require('fs');module.exports = function(app){    fs.readdirSync(__dirname).forEach(function(file) {        if (file == "index.js") return;        var name = file.substr(0, file.indexOf('.'));        require('./' + name)(app);    });}然后将路由文件放在routes目录中,如下所示:路线/ test1.jsmodule.exports = function(app){    app.get('/test1/', function(req, res){        //...    });    //other routes..}重复那个我需要的次数,然后最终在app.js放置require('./routes')(app);

德玛西亚99

即使这是一个较老的问题,我在这里偶然发现了寻找类似问题的解决方案。在尝试了一些解决方案之后,我最终走向了一个不同的方向,并认为我会为其他任何人在这里添加我的解决方案。在express 4.x中,您可以获取路由器对象的实例并导入包含更多路由的另一个文件。您甚至可以递归执行此操作,以便您的路由导入其他路由,从而允许您创建易于维护的URL路径。例如,如果我的'/ tests'端点已经有一个单独的路由文件,并且想为'/ tests / automated'添加一组新的路由,我可能想要将这些'/ automated'路由分解为另一个文件到保持我的'/ test'文件小而易于管理。它还允许您通过URL路径将路由逻辑分组,这非常方便。./app.js的内容:var express = require('express'),    app = express();var testRoutes = require('./routes/tests');// Import my test routes into the path '/test'app.use('/tests', testRoutes);./routes/tests.js的内容var express = require('express'),    router = express.Router();var automatedRoutes = require('./testRoutes/automated');router  // Add a binding to handle '/test'  .get('/', function(){    // render the /tests view  })  // Import my automated routes into the path '/tests/automated'  // This works because we're already within the '/tests' route so we're simply appending more routes to the '/tests' endpoint  .use('/automated', automatedRoutes);module.exports = router;./routes/testRoutes/automated.js的内容:var express = require('express'),    router = express.Router();router   // Add a binding for '/tests/automated/'  .get('/', function(){    // render the /tests/automated view  })module.exports = router;
打开App,查看更多内容
随时随地看视频慕课网APP