Global Variable in app.js accessible in routes?

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

    I used app.all

    The app.all() method is useful for mapping “global” logic for specific path prefixes or arbitrary matches.

    In my case, I'm using confit for configuration management,

    app.all('*', function (req, res, next) {
        confit(basedir).create(function (err, config) {
            if (err) {
                throw new Error('Failed to load configuration ', err);
            }
            app.set('config', config);
            next();
        });
    });
    

    In routes, you simply do req.app.get('config').get('cookie');

提交回复
热议问题