reggie reggie - 4 months ago 7
Javascript Question

How to get app in router files (in Node/Express app)

My app.js looks like this:

app = express();
setup.configure(app);
//...more stuff (e.g. database setup, middleware definition, etc.)...
var api = require('./routes/api');
app.use('/api', api);
module.exports = app;


In the routes/api.js, I then have routes with middleware like this:

router.get('/myroute',
app.sessionMW,
function (req, res, next) {
//...
});


JSLint flags an error because I declare the
app
variable as global.
If I declare it with
var
, I get an error in the route because app is
undefined
. If I require the app in the routes file with
var app = require('../app')
, I get this error:


Error: Route.get() requires callback functions but got a [object
Undefined]


I would like to properly define the app by doing

var app = express();


But how do I access the app in the routes file?

Answer

You can just pass your app object in your routes/api.js file:

app.js

var api = require('./routes/api')(app); // pass 'app'

routes/api.js

module.exports = function(app) {     
  ...
  router.get('/myroute', app.sessionMW, function (req, res, next) { //... });
  ...      
})
Comments