Sam R.
Sam R.

Reputation: 33

Send different router in app.use() based on URL parameters

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?

Upvotes: 2

Views: 56

Answers (1)

Kingsley Solomon
Kingsley Solomon

Reputation: 480

If you want to save yourself from having to type every single line of app.use, a better approach would be something like this.

const express = require('express');
const app  = express();

app.use(function(req, res, next) {
 console.log('your middlewares');
 next();
})

const routes = [
 '' // an empty string can also serve '/' -> /routes/index.js
 'register',
 'login'
];
for(let i = 0; i < routes.length; i+= 1) {
  app.use('/' + routes[i], require('./routes/' + routes[i]));
}

app.listen(8080, () => console.log('running'));

Here's a link to a working sample - https://repl.it/repls/SwelteringHealthyDistributedcomputing

Upvotes: 1

Related Questions