Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to modularize routing with Node.js Express

I'm building a web app with Express and Node and am trying to factor my routing so that I don't have hundreds of routes in the same file. This site serves different files within the projects directory, so I made a file in routes/ called projectRoutes.jsto handle the routing for project files:

var express = require('express');

module.exports = function() {

    var functions = {}

    functions.routeProject = function(req, res) {
        res.render('pages/projects/' + req.params.string, function(err, html) {
            if (err) {
                res.send("Sorry! Page not found!");
            } else {
                res.send(html);
           }
       });
   };

    return functions;
}

Then, in my routes.js, I have this...

var projectRoutes = require("./projectRoutes");
router.get('/projects/:string', function(req, res) {
    projectRoutes().routeProject(req, res);
});

Is there a better way to structure this functionality within projectRoutes.js? In other words, how can I configure projectRoutes.js so that I can write the follow line of code in index.js:

router.get('/projects/:string', projectRoutes.routeProject);

The above seems like the normal way to handle something like this, but currently the above line throws an error in Node that says the function is undefined.

Thanks for your help!

like image 317
user3757174 Avatar asked Jan 10 '23 04:01

user3757174


1 Answers

You should use the native express router, it was made to solve this exact problem! It essentially lets you create simplified nested routes in a modular way.

For each of your resources, you should separate out your routes into several modules named <yourResource>.js. Those modules would contain all of the routing code as well as any other configuration or necessary functions. Then you would attach them in index.js with:

var apiRoute = router.route('/api')
apiRoute.use('/< yourResource >', yourResourceRouter)

For example, if you had a resource bikes:

In index.js:

var apiRoute = router.route('/api')
  , bikeRoutes = require('./bikes')

apiRoute.use('/bikes', bikeRoutes)

Then in bike.js:

var express = require('express')
  , router = express.Router()
  , bikeRoutes = router.route('/')

bikeRoutes.get(function (req, res) {
    res.send('api GET request received')
});

module.exports = bikeRoutes

From there its easy to see that you can build many different resources and continually nest them.

A larger of example of connecting the routes in index.js would be:

var apiRoute = router.route('/api')
  , bikeRoutes = require('./bikes')
  , carRoutes = require('./cars')
  , skateboardRoutes = require('./skateboards')
  , rollerskateRoutes = require('./rollerskates')

// routes
apiRoute.use('/bikes', bikeRoutes)
apiRoute.use('/cars',  carRoutes)
apiRoute.use('/skateboards', skateboardRoutes)
apiRoute.use('/rollerskates', rollerskateRoutes)

Each router would contain code similar to bikes.js. With this example its easy to see using express's router modularizes and makes your code base more manageable.

like image 147
agconti Avatar answered Jan 13 '23 09:01

agconti