1252748 1252748 - 1 month ago 9
Javascript Question

Correct/Concisest way to nest routers with Express

I can set up two routes like this

index.js

var express = require('express');
var app = express();
var router = express.Router();
const PORT = 3001;

app.get('/', function(req, res){
res.send('hello app');
});

app.use('/routes', require('./routes'));

app.listen(PORT, function(){
console.log('listening on port:', PORT);
});


./routes/index.js

var express = require('express');
var app = express();
var router = express.Router();

router.use('/sub1', require('./sub1'));
router.use('/sub2', require('./sub2'));

module.exports = router;


./routes/sub1.js

var express = require('express');
var app = express();
var subOneRouter = express.Router();

subOneRouter.get('/', function(req, res){
res.json({route: 'sub1-base'});
});

subOneRouter.get('/:id', function(req, res){
res.json({'route': 'sub1-base', 'id': req.params.id});
});

module.exports = subOneRouter;


For brevity ./routes/sub2.js looks exactly the same, but its variables are named subTwo

What is the shortest way to nest sub2 under sub1? Within index.js I have tried

var subOne = router.use('/sub1', require('./sub1'));
subOne.use('/sub2', require('./sub2'));


But that didn't work at all. Within index.js

router.use('/sub1/:id/sub2', require('./sub2'));
//localhost:3000/sub1/123/sub2/456 => { "route": "sub2-base","id":"456"}


Does work, but it seems it could get verbose and difficult to maintain if the structure got much longer. What's the best way to do this? Is there a shorter way to nest these?

Answer

Your code in index.js makes it difficult to understand what you want. So far I understand you want a route like /sub1/:id/sub2 but more easy to write and maintain and inside index.js.

So yes you can do it and it is quite simple. You just need to require sub1 and sub2 and use sub2 in sub1, then you can mount sub1 on the router. Ex:

var sub1= require('./sub1');
var sub2 = require('./sub2');
sub1.use(sub2);
router.use('/sub1:id', sub1);

So your index.js becomes,

var express = require('express');
var app = express();
var router = express.Router();
const PORT = 3001;

app.get('/', function(req, res){
    res.send('hello app');
});

var sub1= require('./sub1');
var sub2 = require('./sub2');
sub1.use(sub2);

router.use('/sub1:id', sub1);

app.listen(PORT, function(){
    console.log('listening on port:', PORT);
});

This wouldn't be very difficult to maintain. Let me know if this isn't what you are looking for.