app.js中的全局变量可以在路由中访问吗?

Tec*_*upe 81 node.js express

如何设置变量app.js并使其在所有路径中可用,至少index.js位于路径中的文件中.使用快速框架和node.js

Man*_*ndy 80

使用快速对象上可用的"set"和"get"方法实际上很容易做到这一点.

示例如下,假设您有一个名为config的变量,其中包含您希望在其他位置可用的配置相关内容:

在app.js中:

var config = require('./config');

app.configure(function() {
  ...
  app.set('config', config); 
  ...
}
Run Code Online (Sandbox Code Playgroud)

在routes/index.js中

exports.index = function(req, res){
  var config = req.app.get('config');
  // config is now available
  ...
}
Run Code Online (Sandbox Code Playgroud)

  • 对于后来者:app.configure在express 4.x中删除 (44认同)

Jes*_*ton 60

要创建一个全局变量,只需在没有var关键字的情况下声明它.(一般来说,这不是最佳实践,但在某些情况下它可能很有用 - 只要小心,因为它会使变量在任何地方都可用.)

这是visionmedia/screenshot-app的一个例子

文件app.js:

/**
 * Module dependencies.
 */

var express = require('express')
  , stylus = require('stylus')
  , redis = require('redis')
  , http = require('http');

app = express();

//... require() route files
Run Code Online (Sandbox Code Playgroud)

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');
});

//...
Run Code Online (Sandbox Code Playgroud)

  • 作为一个注释,通常更好的是明确地传递变量并实例化它们,因此你不会在应用程序的其他地方意外地将ref归零,或者你有什么. (5认同)
  • 保罗指出,这是非常糟糕的形式.我建议下面提到的注射模式.是的,更多锅炉板代码,所以它看起来不"漂亮",但它确保你的代码是模块化的...如果这不是你的最后一个项目,你会喜欢的东西;) (3认同)
  • 有人可以解释为什么这可以参考Javascript的语义吗?“ app”与哪个范围相关联? (2认同)
  • 我认为这个答案不应该标记为“正确”。 (2认同)

Ali*_*Ali 46

一个巧妙的方法是使用app.localsExpress本身提供的. 是文档.

// 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;
}
Run Code Online (Sandbox Code Playgroud)


Vad*_*hev 28

要声明一个全局变量,您需要使用全局对象.与global.yourVariableName类似.但这不是一个真正的方式.要在模块之间共享变量,请尝试使用注入样式

someModule.js:

module.exports = function(injectedVariable) {
    return {
        somePublicMethod: function() {
        },
        anotherPublicMethod: function() {
        },
    };
};
Run Code Online (Sandbox Code Playgroud)

app.js

var someModule = require('./someModule')(someSharedVariable);
Run Code Online (Sandbox Code Playgroud)

或者你可以使用代理对象来做到这一点.像枢纽一样.

someModule.js:

var hub = require('hub');

module.somePublicMethod = function() {
    // We can use hub.db here
};

module.anotherPublicMethod = function() {
};
Run Code Online (Sandbox Code Playgroud)

app.js

var hub = require('hub');
hub.db = dbConnection;
var someModule = require('./someModule');
Run Code Online (Sandbox Code Playgroud)


Sha*_*man 9

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

global.mySpecialVariable = "something"
Run Code Online (Sandbox Code Playgroud)

then in any routes you can get it:

console.log(mySpecialVariable)
Run Code Online (Sandbox Code Playgroud)


小智 7

简而言之,这里有解释:

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

所以你正在使用一组Node模块,也许是像Express.js这样的框架,突然觉得有必要让一些变量成为全局变量.如何在Node.js中创建全局变量?

对此的最常见建议是"声明不带var关键字的变量"或"将变量添加到全局对象"或"将变量添加到GLOBAL对象".你用哪一个?

首先,让我们分析全局对象.打开终端,启动Node REPL(提示).

> 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'
Run Code Online (Sandbox Code Playgroud)


Joh*_*don 5

这是一个有用的问题,但通过提供实际的代码示例可能会更有用。即使链接的文章实际上也没有显示实现。因此,我谦虚地提出:

在您的app.js文件中,文件的顶部:

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');
Run Code Online (Sandbox Code Playgroud)

app.js 不会有任何app.get()方法引用。将这些保留在各个路由文件中定义。

routes/index.js

require('./main');
require('./users');
Run Code Online (Sandbox Code Playgroud)

最后,一个实际的路由文件,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
Run Code Online (Sandbox Code Playgroud)


Wil*_*ern 5

我的首选方式是使用循环依赖*,节点支持

  • 在 app.js 中定义var app = module.exports = express();为您的首要任务
  • 现在事后所需的任何模块都可以var app = require('./app')访问它


应用程序.js

var express   = require('express');
var app = module.exports = express(); //now app.js can be required to bring app into any file

//some app/middleware, config, setup, etc, including app.use(app.router)

require('./routes'); //module.exports must be defined before this line
Run Code Online (Sandbox Code Playgroud)


路线/index.js

var app = require('./app');

app.get('/', function(req, res, next) {
  res.render('index');
});

//require in some other route files...each of which requires app independently
require('./user');
require('./blog');
Run Code Online (Sandbox Code Playgroud)


Cod*_*ker 5

这是很简单的事情,但人们的答案既令人困惑又复杂。

让我向您展示如何在应用程序中设置全局变量express。因此您可以根据需要从任何路线访问它。

假设您想从主/路线设置一个全局变量

router.get('/', (req, res, next) => {

  req.app.locals.somethingNew = "Hi setting new global var";
});
Run Code Online (Sandbox Code Playgroud)

所以你将从所有路由中获得 req.app 。然后你必须使用locals来设置全局数据。就像上面显示的那样,你已经准备好了。现在 我将向您展示如何使用该数据

router.get('/register', (req, res, next) => {

  console.log(req.app.locals.somethingNew);
});
Run Code Online (Sandbox Code Playgroud)

与上面一样,register您访问数据的路线已提前设置。

这就是让这个东西发挥作用的方法!