简体   繁体   中英

How to define global variables in node.js

I have a module called routeEnforcer.js which contains multiple functions and an object variable called globalUser.

This is the routeEnforcer.js module

I have another module called routeHandler.js which handles all the routes the application takes. I set the routeEnforcer.globalUser to the retrieved user object from the database. When I display the value using console.log, the object is set correctly. When I display the same object in another function, the object is "undefined". I've spent hours trying to figure this out. Can anyone help?

This is the routeHandler.js module showing the required variables.

This is routeHandler.js module showing the post method for login where the routeEnforcer.globalUser is set and displayed successfully.

This is routeHandler.js module showing the get method for the properties view where the routeEnforcer.globalUser variable displays as "undefined".

Create in global object

Ex: global.nameVar = 'value'

尝试像这样导出变量: module.exports = 'value' // or object or function or whatever you want ,您可以再次调用它。

Thanks for your help. I have solved my problem. One thing I forgot to mention was that this app is using the Angular.js framework. My solution was passing the value into the $http.get method within the controller class.

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