Global Variable in app.js accessible in routes?

前端 未结 13 1437
南笙
南笙 2020-11-28 21:29

How do i set a variable in app.js and have it be available in all the routes, atleast in the index.js file located in routes. using the express fra

相关标签:
13条回答
  • 2020-11-28 22:34

    My preferred way is to use circular dependencies*, which node supports

    • in app.js define var app = module.exports = express(); as your first order of business
    • Now any module required after the fact can var app = require('./app') to access it


    app.js

    var express   = require('express');
    var app = module.exports = express(); //now app.js can be required to bring app into any file
    
    //some app/middleware, config, setup, etc, including app.use(app.router)
    
    require('./routes'); //module.exports must be defined before this line
    


    routes/index.js

    var app = require('./app');
    
    app.get('/', function(req, res, next) {
      res.render('index');
    });
    
    //require in some other route files...each of which requires app independently
    require('./user');
    require('./blog');
    
    0 讨论(0)
提交回复
热议问题