简体   繁体   中英

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. This includes (.pug files js files).

I have tried creating a global variable with res.locals.user = "user"; . When trying to access the variable in .pug files it works and will provide the information stored in the variable.

//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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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