Global Variable in app.js accessible in routes?

前端 未结 13 1666
南笙
南笙 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

    A neat way to do this is to use app.locals provided by Express itself. Here is the documentation.

    // In app.js:
    app.locals.variable_you_need = 42;
    
    // In index.js
    exports.route = function(req, res){
        var variable_i_needed = req.app.locals.variable_you_need;
    }
    

提交回复
热议问题