Global Variable in app.js accessible in routes?

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

    the easiest way is to declare a global variable in your app.js, early on:

    global.mySpecialVariable = "something"
    

    then in any routes you can get it:

    console.log(mySpecialVariable)
    
    0 讨论(0)
  • 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');
    });
    
    //...
    
    0 讨论(0)
  • 2020-11-28 22:25

    Here are explain well, in short:

    http://www.hacksparrow.com/global-variables-in-node-js.html

    So you are working with a set of Node modules, maybe a framework like Express.js, and suddenly feel the need to make some variables global. How do you make variables global in Node.js?

    The most common advice to this one is to either "declare the variable without the var keyword" or "add the variable to the global object" or "add the variable to the GLOBAL object". Which one do you use?

    First off, let's analyze the global object. Open a terminal, start a Node REPL (prompt).

    > global.name
    undefined
    > global.name = 'El Capitan'
    > global.name
    'El Capitan'
    > GLOBAL.name
    'El Capitan'
    > delete global.name
    true
    > GLOBAL.name
    undefined
    > name = 'El Capitan'
    'El Capitan'
    > global.name
    'El Capitan'
    > GLOBAL.name
    'El Capitan'
    > var name = 'Sparrow'
    undefined
    > global.name
    'Sparrow'
    
    0 讨论(0)
  • 2020-11-28 22:25

    this is pretty easy thing, but people's answers are confusing and complex at the same time.

    let me show you how you can set global variable in your express app. So you can access it from any route as needed.

    Let's say you want set a global variable from your main / route

    router.get('/', (req, res, next) => {
    
      req.app.locals.somethingNew = "Hi setting new global var";
    });
    

    So you'll get req.app from all the routes. and then you'll have to use the locals to set global data into. like above show you're all set. now I will show you how to use that data

    router.get('/register', (req, res, next) => {
    
      console.log(req.app.locals.somethingNew);
    });
    

    Like above from register route you're accessing the data has been set earlier.

    This is how you can get this thing working!

    0 讨论(0)
  • 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
    
    0 讨论(0)
  • 2020-11-28 22:30

    I solved the same problem, but I had to write more code. I created a server.js file, that uses express to register routes. It exposes a function,register , that can be used by other modules to register their own routes. It also exposes a function, startServer , to start listening to a port

    server.js
    
    const express = require('express');
    const app = express();
    
    const register = (path,method,callback) => methodCalled(path, method, callback)
    
    const methodCalled = (path, method, cb) => {
      switch (method) {
        case 'get':
          app.get(path, (req, res) => cb(req, res))
          break;
        ...
        ...  
        default:
          console.log("there has been an error");
      }
    }
    
    const startServer = (port) => app.listen(port, () => {console.log(`successfully started at ${port}`)})
    
    module.exports = {
      register,
      startServer
    }
    

    In another module, use this file to create a route.

    help.js
    
    const app = require('../server');
    
    const registerHelp = () => {
      app.register('/help','get',(req, res) => {
        res.send("This is the help section")
      }),
      app.register('/help','post',(req, res) => {
        res.send("This is the help section")
      })}
    
    module.exports = {
      registerHelp
    }
    

    In the main file, bootstrap both.

    app.js
    
    require('./server').startServer(7000)
    require('./web/help').registerHelp()
    
    0 讨论(0)
提交回复
热议问题