简体   繁体   English

如何避免使用Express将所有路由添加到NodeJS中的app对象?

[英]How can I avoid adding all routes to the app object in NodeJS with Express?

In my NodeJS application using Express it seems like I need to add all my "get" paths to the "app" express variable. 在使用Express的NodeJS应用程序中,似乎需要将所有“获取”路径添加到“ app”表达变量中。 It would be nice if I only had to register the module and not register each route. 如果我只需要注册模块而不注册每个路由,那将是很好的。 I'm coming from an ASP.NET MVC background where if I make a Controller class then it gets automatically routed to. 我来自ASP.NET MVC背景,如果我创建Controller类,它将自动路由到该类。 Is there a way to make Express work like this or do I need to add the routes to this one ever growing file of paths? 有没有办法使Express像这样工作,还是我需要将路由添加到这个不断增长的路径文件中? Can it do some sort of reflection or is there a way to set this up? 它可以进行某种反射还是有办法进行设置?

var app = express();

// all environments
app.set('port', process.env.PORT || 3000);
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'jade');
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.json());
app.use(express.urlencoded());
app.use(express.methodOverride());
app.use(app.router);

import stylus = require('stylus');
app.use(stylus.middleware(path.join(__dirname, 'public')));
app.use(express.static(path.join(__dirname, 'public')));

// development only
if ('development' == app.get('env')) {
    app.use(express.errorHandler());
}

app.get('/', routes.index);
app.get('/users', user.list);


http.createServer(app).listen(app.get('port'), function () {
    console.log('Express server listening on port ' + app.get('port'));
});

With Express 4 you can mount Routers (like miniature Express apps) on a base path, so you could set up a Router to handle all /user/* paths, one for /article/* paths, etc.: 使用Express 4,您可以在基本路径上安装路由器(例如微型Express应用程序),因此您可以设置路由器以处理所有/user/*路径,一个用于/article/*路径,等等:

app.use('/user', routers.user);
app.use('/article', routers.article);
// ...

You can then put the logic for these routers in separate files and just require and use them in wherever it makes sense (eg in your main app.js or even inside another router). 然后,您可以将这些路由器的逻辑放在单独的文件中,并仅在需要的地方使用它们(例如,在主app.js ,甚至在另一个路由器中)。

See this Express 4 docs for more details. 有关更多详细信息,请参阅此Express 4文档

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

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