user2727195
user2727195

Reputation: 7330

Express Router with a sub-router

Let's say parent module has a router with public requests using

Parent Module

app.get("/speakers",...
app.get("/agenda",... etc.

and another wild card route which actually delegates the request to child module to handle all of it's nested operations which parent module doesn't need to know or care about.

app.all("/admin/*/*" //delegates task to another module

Child Module

child module receives the admin request but then it has to deal with all uri's, routes and params

like

/admin/login
/admin/dashboard/events
/admin/dashboard/events/1 //could go deeper

How to have another level of route parsing or engine at this nested level?

Upvotes: 1

Views: 2374

Answers (1)

Andrew Lavers
Andrew Lavers

Reputation: 8141

You can organize your admin routes as a separate module like this:

/routes/admin.js

var login = function(req, res, next) {
    res.end();
}

// etc...

module.exports = express.Router()
    .post('/login', login)
    .get('/dashboard/events', listEvents)
    .get('/dashboard/events/:id', findEvent);

Then in your app.js:

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

Note that the routes you defined in the admin route are all going to be relative to the root you specified as the first param to app.use.

Upvotes: 3

Related Questions