简体   繁体   English

Express.js-用于管理所有路线的单个路线文件

[英]Express.js - Single routes file that manages all the routes

I am kinda new to express.js and did not find a matching answer to my problem yet. 我是express.js的新手,但尚未找到与我的问题相匹配的答案。

I've got an express app with a folder structure like this: 我有一个具有这样的文件夹结构的快速应用程序:

app/
|--app.js
|--routes/
|--|--index.js
|--|--news.js
|--|--users.js 
|--some_other_folders/

As for now, I've got my routes managed in the app.js, like this: 到目前为止,我已经在app.js中管理了路由,如下所示:

var index = require('./routes/index');
var users = require('./routes/users');
...
app.use('/', index);
app.use('/users', users);
...

This works fine, but I originally wanted to manage all my routes with only one file, so that I only need to reference this file in the app.js. 这可以正常工作,但是我最初只想用一个文件来管理所有路由,因此我只需要在app.js中引用该文件。

Something like this: 像这样:

[app.js]
var routes = require('./routes/routes');
app.use('/', routes);


[routes/routes.js]
...
router.get('/', function(req, res) {
  res.render('index.html');
});

require('./users'); // This is meant to refer to the users routes
...

Is there a way to include my other route files (like users, news, ...) into the "main"-route file? 有没有办法将我的其他路由文件(例如用户,新闻等)包含到“主”路由文件中?

Or are there maybe other best-practices to mange routes within express.js? 或者,也许还有其他最佳实践来管理express.js中的路由?

Thank you so much for your help! 非常感谢你的帮助!

Yes, there are good way to do this 是的,有很好的方法可以做到这一点

[app.js]
var routes = require('./routes/routes')(app);

[routes/routes.js]
var user = require('./user'); // get user controllers

module.exports = function(app) {
    app.get('/', function() { ... });
    app.get('/another-path', function() { ... });

    app.get('/user/:id', user.display);
    app.post('/user/:id', user.update);
};
[routes/user.js]
module.exports.display = function(req, res) {
    ...
    res.render('user', data);
}
module.exports.update = function(req, res) {
    ...
    res.render('user', data);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM