如何在NodeJS的其他模块中访问app.locals?

时间:2019-03-31 03:14:10

标签: node.js

使用我的主要server.js文件,导出了我的应用变量:

//Assume there's other code in this file of course
    var app = express();
    app.locals.database = //here's my DB connection. This variable works perfectly within the server.js file!
    module.exports = app;

我将其导入了另一个模块:

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

但是我无法访问app.locals变量?我在server.js中设置了其中一些(例如数据库连接信息),但出现此错误:

TypeError: Cannot read property 'database' of undefined

当尝试阅读时:

app.locals.database

我在做什么错了?

注意:在我的其他模块应用中,{}是,但是当我在原始模块中检查它时,它具有大量信息。

1 个答案:

答案 0 :(得分:0)

根据文档Once set, the value of app.locals properties persist throughout the life of the application

对于您而言,在导出应用程序时,可以在文件级别(不确定正确的术语)访问该文件,这是您作为app.locals.database导入的位置(记住app是一个对象)。

但是,如果您想访问未导入的其他地方,express可以通过req.app.locals将其提供给所有中间件使用。文档清楚地提到了Local variables are available in middleware via req.app.locals

还可以查看此SO question,它使您对app.localsreq.locals有了很好的了解