Global Variable in app.js accessible in routes?

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

    To make a global variable, just declare it without the var keyword. (Generally speaking this isn't best practice, but in some cases it can be useful - just be careful as it will make the variable available everywhere.)

    Here's an example from visionmedia/screenshot-app

    file app.js:

    /**
     * Module dependencies.
     */
    
    var express = require('express')
      , stylus = require('stylus')
      , redis = require('redis')
      , http = require('http');
    
    app = express();
    
    //... require() route files
    

    file routes/main.js

    //we can now access 'app' without redeclaring it or passing it in...
    
    /*
     * GET home page.
     */
    
    app.get('/', function(req, res, next){
      res.render('index');
    });
    
    //...
    

提交回复
热议问题