Global Variable in app.js accessible in routes?

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

    This was a helpful question, but could be more so by giving actual code examples. Even the linked article does not actually show an implementation. I, therefore, humbly submit:

    In your app.js file, the top of the file:

    var express = require('express')
    , http = require('http')
    , path = require('path');
    
    app = express(); //IMPORTANT!  define the global app variable prior to requiring routes!
    
    var routes = require('./routes');
    

    app.js will not have any reference to app.get() method. Leave these to be defined in the individual routes files.

    routes/index.js:

    require('./main');
    require('./users');
    

    and finally, an actual routes file, routes/main.js:

    function index (request, response) {
        response.render('index', { title: 'Express' });
    }
    
    app.get('/',index); // <-- define the routes here now, thanks to the global app variable
    

提交回复
热议问题