Global Variable in app.js accessible in routes?

前端 未结 13 1684
南笙
南笙 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:09

    It is actually very easy to do this using the "set" and "get" methods available on an express object.

    Example as follows, say you have a variable called config with your configuration related stuff that you want to be available in other places:

    In app.js:

    var config = require('./config');
    
    app.configure(function() {
      ...
      app.set('config', config); 
      ...
    }
    

    In routes/index.js

    exports.index = function(req, res){
      var config = req.app.get('config');
      // config is now available
      ...
    }
    

提交回复
热议问题