'Passing global variable to another controller file in Node.js
I have created a global variable (userEmail) which holds the value of current user. Post request handles the authorization and assigns the email of current user to that global variable. Issue comes when exporting that global variable (userEmail) to another file. Another file reads it as 'not assigned', maybe because the module.export runs before the route.post. What can be the solution to have the global variable in another file altered by the route.post assignment to the current user?
var userEmail = 'not assigned';
route.get('/', (req, res) => {
res.render('signIn');
})
route.post('/', (req, res) => {
let email = req.body["sign-in-email"];
let password = req.body["sign-in-password"];
let errorMessage = '';
userModel.findOne({ 'email': email }, 'email password balance', function (err, user) {
if (err) return handleError(err);
if (email == user.email) {
if (bcrypt.compareSync(password, user.password)) { // function returns true if password matched the database hashed password
userEmail = user.email;
exports = {userEmail};
res.render('dashboard', { email: userEmail , balance: user.balance})
console.log(userEmail)
} else {
errorMessage = 'Invalid password'
res.render('home', { errorMessage: errorMessage });
};
} else {
errorMessage = 'User Not Found'
res.render('home', { errorMessage: errorMessage });
}
});
})
module.exports = {route, userEmail};
Solution 1:[1]
NodeJS has a global variable that you can use to manage global values. Here is a sample for the global variable, If you have a logger class and you want to have its instance globally in your environment, you can do like this,
global.logger = new Logger()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Shohidul Bari |
