Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Kirill Malikov
8,301 PointsNodejs - How can i use created object in few routers?
I try to bind it to request.session or request.user, but have same error - 'undefined function'. How can i use created req.session.idle = new SteamIdle('user', 'pass') in /start router in /stop router, if i access them directly by url (localhost:3000/start and localhost:3000/stop)?
router.get('/start', checkAuth, function(req, res, next) {
res.setHeader("Content-Type", "application/json");
var data = {
statusCode: 1,
status: 'connected'
};
if (typeof req.session.idle == "undefined")
req.session.idle = new SteamIdle('user', 'pass'); // created instance
if (!req.session.idle.isLogin){
req.session.idle.connect();
// req.session.idle.disconnect(); this will work here, but not in /stop router
}
res.send(data);
});
router.get('/stop', checkAuth, function(req, res, next) {
res.setHeader("Content-Type", "application/json");
var data = {
status: 'done'
};
if (typeof req.session.idle != "undefined"){
req.session.idle.disconnect(); //undefined function, is there any way to make it work?
delete req.session.idle;
}
res.send(data);
});
SteamIdle
function SteamIdle(user, pass){
var self = this;
self.userName = user;
self.password = pass;
// Main func
self.disconnect = function() {
console.log('disconnect');
}
self.connect = function(auth){
console.log('start work for user ' + self.userName);
}
}
module.exports = SteamIdle;
1 Answer
Kirill Malikov
8,301 PointsI found a solution. I use express framework for nodejs. In Express API - i found app.locals propertis that has global scope. So i creat req.app.idle = new SteamIdle('user', 'pass') object and can access it's disconnect function at /stop router.