如何在少数路由器中使用创建的对象?

时间:2015-10-17 12:37:59

标签: node.js

我尝试将它绑定到request.session或request.user,但是有相同的错误 - 'undefined function'。我如何使用创建的req.session.idle =新的SteamIdle('user','pass')/ start路由器/ stop路由器,如果我直接通过url访问它们(localhost:3000 / start和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;

2 个答案:

答案 0 :(得分:0)

好的,你试图从chrome或某些浏览器发送请求,问题是他们发送req两次(其他来获取会弄乱你的会话对象的favicon)

从某些rest client邮递员那里试试,vl work

在我的代码中,我使用req.session.idle = {'a':'1'}并且能够使用邮递员在停止路线中获取此json

答案 1 :(得分:0)

我找到了解决方案。我为nodejs使用express框架。在Express API - 我找到了具有全局范围的app.locals属性。所以我创建了req.app.idle = new SteamIdle('user','pass')对象,可以在/ stop路由器上访问它的断开功能。