I am writing a program in Express (with Pug as the templating engine) that uses routers in external documents. I am trying to avoid having to create a separate app.use() for each page, but I can't figure out how to change what router I used based on the URL. I can store req.params.page in a global variable, but that gets really messy and breaks easily.
Ideally, I would like to do something like this - being able to pass information from the first function into the next routes[] parameter.
// route static urls
const registerRouter = require('./routes/register')
const indexRouter = require('./routes/index')
const loginRouter = require('./routes/login')
// (i just hardcoded this for clarity)
const routes = {register: registerRouter, index: indexRouter, login: loginRouter}
app.use('/:page', (req, res, next) => {
req.info = generatePayload(req, res, next) /* verifies the user's jwt and passes back the payload*/
req.page = req.params.page
next()
}, routes[req.page])
Here's a snippet of what my routers look like
const express = require('express')
const router = express.Router()
// get & render page
router.all('/', function(req, res, next) {
req.info.title = "register"
res.render('register', req.info)
})
module.exports = router
Is there any way I could achieve this, or is there a better way I should be approaching it?