在我的NodeJS express
应用程序中,我有app.js
,它有一些常见的路由。然后在wf.js
文件中,我想定义更多的路由。
如何让app.js
识别wf.js
文件中定义的其他路由处理程序?
简单的请求似乎不起作用。
发布于 2011-05-19 22:05:39
如果您想将路由放在一个单独的文件中,例如routes.js
,您可以这样创建routes.js
文件:
module.exports = function(app){
app.get('/login', function(req, res){
res.render('login', {
title: 'Express Login'
});
});
//other routes..
}
然后,您可以通过以下方式从传递app
对象的app.js
请求它:
require('./routes')(app);
看一下这些示例:https://github.com/visionmedia/express/tree/master/examples/route-separation
发布于 2016-05-19 04:11:08
在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 '/tests'
.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;
发布于 2011-05-20 04:01:26
基于@ShadowCloud的示例,我能够动态地将所有路由包含在一个子目录中。
routes/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目录中,如下所示:
routes/test1.js
module.exports = function(app){
app.get('/test1/', function(req, res){
//...
});
//other routes..
}
根据需要重复多次,最后在app.js中放置
require('./routes')(app);
https://stackoverflow.com/questions/6059246
复制相似问题