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?
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
, andres.app
, respectively.
This property holds a reference to the instance of the Express application that is using the middleware.
res.app
is identical to thereq.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:
node server.js
http://127.0.0.1:3000/test-route
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) { //... });
...
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With