passatgt passatgt - 5 months ago 13
Node.js Question

How to properly access the app variable set by express in a node.js app?

I'm building a node.js server and my folder structure looks like this:


  • server.js

  • app/routes.js

  • app/routes/users.js



My problem is that i'm not sure how can i use the
app
variable inside the users.js file. Do i have to require and setup express again in this file or is there a better/easier way to do it? Here is my sample code(just the bare minimum to understand my problem):

server.js

// Include our packages in our main server file
var express = require('express');
var stormpath = require('express-stormpath');
var app = express();

// Init Stormpath for user management and authentication
app.use(stormpath.init(app));

// Load routes
require('./app/routes')(app);

// Start the server
app.listen(process.env.PORT);

// Stormpath will let you know when it's ready to start authenticating users.
app.on('stormpath.ready', function () {
console.log('Your server is running on port ' + port + '.');
});


app/routes.js

// Import dependencies
const express = require('express');
const stormpath = require('express-stormpath');

// Export the routes for our app to use
module.exports = function(app) {
// Create API group routes
const apiRoutes = express.Router();

// User management: get users, invite users, view user profile
var UsersRoute = require('./routes/users');
apiRoutes.get('/memberinfo', stormpath.loginRequired, UsersRoute.memberInfo);

// Set url for API group routes
app.use('/', apiRoutes);
};


app/routes/users.js

// Protected route test
module.exports.memberInfo = function(req, res){
//how do i access the "app" here?
res.status(200).send({ user: req.user });
}

Answer

In your .memberInfo method, you can use req.app to access the app object that is associated with that request.

In cases where you aren't passed a req object that you can use in this way, then you need to initialize the module by calling a method on it and passing it the app object and the module can then store the app object locally so it can use it when desired.