3 回答

TA貢獻1865條經驗 獲得超7個贊
在@ShadowCloud的例子的基礎上,我能夠動態地包含子目錄中的所有路由。
路線/ index.js
var 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.js
module.exports = function(app){
app.get('/test1/', function(req, res){
//...
});
//other routes..
}
重復那個我需要的次數,然后最終在app.js放置
require('./routes')(app);

TA貢獻1770條經驗 獲得超3個贊
即使這是一個較老的問題,我在這里偶然發現了尋找類似問題的解決方案。在嘗試了一些解決方案之后,我最終走向了一個不同的方向,并認為我會為其他任何人在這里添加我的解決方案。
在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;
- 3 回答
- 0 關注
- 1073 瀏覽
添加回答
舉報