简体   繁体   English

从外部.js文件中的App.js文件访问全局变量(Express)

[英]Accessing Global Variables from App.js file in external .js files (Express)

I am currently working on creating a global user object for my Node app (that will eventually use the pug view engine), and would like to be able to access the object in every js file that pertains to the project. 我目前正在为我的Node应用程序创建一个全局用户对象(最终将使用pug视图引擎),并希望能够访问与项目相关的每个js文件中的对象。 This includes (.pug files js files). 这包括(.pug文件js文件)。

I have tried creating a global variable with res.locals.user = "user"; 我尝试用res.locals.user = "user";创建一个全局变量res.locals.user = "user"; . When trying to access the variable in .pug files it works and will provide the information stored in the variable. 当尝试访问.pug文件中的变量时,它可以工作并提供存储在变量中的信息。

//Created the global variable which only works with .pug files.
app.use((req,res,next)=> {
    res.locals.user = 'user';
    next();
});
//From file outside of app.js. returns undefined
console.log(req.user);

Ideally, I would like the user object to be accessible from every file in the project. 理想情况下,我希望可以从项目中的每个文件访问用户对象。 For example, since the variable is equal to 'user' it should atleast log user in my console. 例如,由于变量等于'user',它应该至少在我的控制台中的日志用户。

Turns out that for this to work the global variable must be set as 事实证明,要使其工作,必须将全局变量设置为

app.use((req,res,next)=> {
    app.locals.user = 'user';
    next();
});

Then it will need to be accessed as 然后它需要被访问为

console.log(req.app.locals.user);

in other files 在其他文件中

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM