Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 807
reggie Avatar asked Jul 09 '15 12:07

reggie


2 Answers

According to the Express 4.x docs, you can access the app object easily through the request and response objects using req.app & res.app

The Express application object can be referred from the Request object and the Response object as req.app, and res.app, respectively.

  • req.app

    This property holds a reference to the instance of the Express application that is using the middleware.

  • res.app

    res.app is identical to the req.app property in the Request object.

code-example:

server.js:

var path = require('path');
var express = require('express');

var app = express();

app.set('firends', 'nodejs, python');

var page = require(path.join(
    __dirname,
    'page'
));
app.use('', page);

app.listen(3000);

page.js:

var express = require('express');

var router = express.Router();
router.get('/test-route', function (req, res) {
    var app = req.app; // get app object
    res.send('firends are: ' + app.get('firends')); // get firends from app
});

module.exports = router;

Tips:

  • server.js and page.js are in the same folder.
  • run with command: node server.js
  • visit with url: http://127.0.0.1:3000/test-route
like image 182
Damanveer Singh Avatar answered Nov 17 '22 11:11

Damanveer Singh


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) { //... });
  ...      
})
like image 9
hassansin Avatar answered Nov 17 '22 11:11

hassansin