简体   繁体   English

维护和组织ExpressJS路线

[英]Maintaining and organizing ExpressJS routes

I'm new to NodeJS and Express moving from PHP. 我是从PHP迁移到NodeJS和Express的新手。 I have been following online tutorials on how to build web apps with Express and it has been an eye opener. 我一直在关注有关如何使用Express构建Web应用程序的在线教程,这令人大开眼界。 So I decided to work on a project with just JavaScript. 因此,我决定只使用JavaScript进行项目。 Problem is after adding a few route definitions in Express, I'm having trouble keeping track of my Express routes and fear it'll get even larger with time. 问题是在Express中添加了一些路由定义后,我无法跟踪Express路由,并且担心它会随着时间的流逝而变得更大。 Currently I have almost 45 lines (yes, I have a lot of route, some serve HTML templates files and other just return JSON for my Angular frontend). 目前,我有近45行(是的,我有很多路线,一些提供HTML模板文件,而另一些则为Angular前端返回JSON)。 Is there any better way to manage this before it gets out of hand? 有什么更好的方法可以解决这个问题吗?

One possible way of organizing the routes is to groups of routes based on functionality and then create separate modules for these groups and then, import these modules to the main app file(app.js or server.js). 组织路由的一种可能方法是根据功能划分路由组,然后为这些组创建单独的模块,然后将这些模块导入主应用程序文件(app.js或server.js)。 For example, I am working on a project that has trading functionality, cash deposit functionality and then some other common tasks. 例如,我正在一个具有交易功能,现金存款功能以及其他一些常见任务的项目。 So, I have created different modules for these routes and put them in a separate directory called routes. 因此,我为这些路由创建了不同的模块,并将它们放置在称为路由的单独目录中。

For example, I have a module named site.js for all the common tasks. 例如,我有一个名为site.js的模块来执行所有常见任务。

module.exports = function(express,app,passport,router){

    router.get('/auth/facebook',passport.authenticate('facebook'));
    //other commin routes   

};

and in my app.js file, I declare the router and then pass in to the modules that contain routes. 然后在我的app.js文件中声明路由器,然后传入包含路由的模块。

var router = express.Router();
app.use('/',router);

require('./routes/site.js')(express,app,passport,router);

If you are using Express version 4, i wrote a module to handle routes in a cleaner less bloated way. 如果您使用的是Express版本4,则我编写了一个模块,以一种更轻松,更轻松的方式处理路由。 Checkout Exroute Module if it fits your current needs and please provide some feedback if it doesnt. Checkout Exroute模块是否适合您当前的需求,如果不合适 ,请提供一些反馈。

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

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