0

Suppose I want to do this:

app.use('/user/login', require('./routes/user.route.js')(variable));

I can't because I will get:

TypeError: Router.use() requires a middleware function but got a undefined

How can I pass variable to user.route constructor?

sfarzoso
  • 1,356
  • 2
  • 24
  • 65

1 Answers1

2

In your user.route.js, you need to export something like this :

module.exports = function (variable) {
    return (req, res, next) => {
        // your middleware
        next()
    }
}

Or with currying (https://wsvincent.com/javascript-currying/):

module.exports = variable => (req, res, next) => {
   const myUsedVariable = variable + 1
   res.send(myUsedVariable)
}

And if you're using express.Router:

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

router.get('/', function(req, res) {
  res.send('Birds home page')
})

module.exports = variable => {
   // do something with your variable
   router.use(function displayVariable(req, res, next) {
      console.log(variable)
      next()
   })

   return router
}
spasfonx
  • 170
  • 7
  • it's a good way to define `var express = require('express')` in each router? – sfarzoso Mar 05 '19 at 13:04
  • 1
    In a performance way ? The require mechanism handle this fine https://stackoverflow.com/questions/8887318/understanding-node-js-modules-multiple-requires-return-the-same-object – spasfonx Mar 05 '19 at 13:10