Reputation: 25
I'm new to NodeJS and Express moving from PHP. I have been following online tutorials on how to build web apps with Express and it has been an eye opener. So I decided to work on a project with just 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. 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). Is there any better way to manage this before it gets out of hand?
Upvotes: 1
Views: 161
Reputation: 415
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). 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.
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.
var router = express.Router();
app.use('/',router);
require('./routes/site.js')(express,app,passport,router);
Upvotes: 2
Reputation: 922
If you are using Express version 4, i wrote a module to handle routes in a cleaner less bloated way. Checkout Exroute Module if it fits your current needs and please provide some feedback if it doesnt.
Upvotes: 0