1
我建立一個服務器的Node.js和我的文件夾結構是這樣的:如何正確訪問由node.js應用程序中的express設置的應用程序變量?
- server.js
- 應用程序/ routes.js
- 應用程序/路由/ users.js
我的問題是,我不知道如何使用users.js文件中的app
變量。我是否需要並在此文件中再次設置表達式,還是有更好/更簡單的方法來執行此操作?下面是我的示例代碼(只是最低限度的理解我的問題):
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 + '.');
});
應用程序/ 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);
};
應用程序/路線/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 });
}