如何在节点JS中处理连续的https请求?

时间:2016-08-24 12:03:48

标签: node.js oauth callback slack asynccallback

我正在尝试构建一个松弛的应用程序并正确配置它我需要做连续的Https获取请求。我使用回调方法来处理它,第一个调用第二个没有任何问题,但第三个从未启动,我的程序卡住了。 这是我的代码:

//CREATE THE app OBJECT
//---------------------

var app = express();
app.use(bodyParser());
var port = process.env.PORT || 5000;



//CALLBACK FUNCTIONS
//------------------

// USE THE SLACK BUTTON TO CREATE THE APP
boutonSlack = function(req, res,next) { 
    res.send('<a href="https://slack.com/oauth/authorize?scope=bot,incoming-webhook,commands&client_id='+process.env.CLIENT_ID+'">' 
                +'<img alt="Add to Slack" height="40" width="139"'
                +'src="https://platform.slack-edge.com/img/add_to_slack.png" '
                +'srcset="https://platform.slack-edge.com/img/add_to_slack.png 1x, '
                +'https://platform.slack-edge.com/img/add_to_slack@2x.png 2x" /></a>');
    console.log('cb0:le bouton slack s\'affiche');
    next();
    app.get('/redirect/',oauthFlow);
};


//GET THE CODE PARAMETER AND PERFORM THE OAUTH FLOW
oauthFlow = function(req, res, next){
    process.env.CODE = req.query.code;
    console.log('cb1 : le code est récupéré');
    https.get('https://slack.com/api/oauth.access?client_id='+process.env.CLIENT_ID+'&client_secret='+process.env.CLIENT_SECRET+'&code='+process.env.CODE, (res) => {
        res.on('data', (chunk) => {
            var result = JSON.parse(chunk);
            process.env.SLACKTOKEN = result.access_token;
            process.env.SLACK_BOT_TOKEN = result.bot.bot_access_token;
            console.log('cb2 : le token est récupéré')
            next();
            app.get('/websocket/',ouvertureWebsocket);
        });
    });
};


//THIS CALLBACK NEVER STARTS
//PERFORM THE rtm.slack METHOD
ouvertureWebsocket = function (req, res, next) {
    console.log("working");
    https.get('https://slack.com/api/rtm.start?token='+process.env.SLACK_BOT_TOKEN, (res) => {
        res.on('data', (chunk) => {
            var result = JSON.parse(chunk);
            console.log(JSON.stringify(result));
            console.log('cb3 : ouverture du web socket');
            next();
        });
    });
    res.end(); 
}



//RUN THE CALLBACK FUNCTIONS
//--------------------------

app.get('/',boutonSlack);
app.listen(port, function () {
  console.log('Ready, listenning port '+port);
});

1 个答案:

答案 0 :(得分:0)

这引起了怀疑:

app.get('/redirect/',oauthFlow);

并不是代码行有什么问题,只是它在'/'路由的处理程序中。通常,您将在顶层定义所有路径处理程序,而不再在任何处理程序中定义。