2016-10-22 221 views
0

我不確定Twilio Authy的register_user()的成功回調是否正在解僱。在我的代碼Twilio Authy回調問題

var authyUsrId; 
//global.authyUsrId; 

app.post('/forTwilio', function(req, res){ 
    // send the received data to Twilio Authy 
    authy.register_user('[email protected]', '8753565612', '91', function(err, res){ 
     //global.authyUsrId = 'world'; 
       authyUsrId = 'world'; 
    }); 
    //res.set("Content-Type","application/json"); 
     res.json({name: 'hello', msg: authyUsrId}); 
    //res.json({name: 'hello', msg: global.authyUsrId}); 
}); 

雖然新用戶被成功添加到Authy和響應狀態是200

我想authyUsrId的值設置爲東西的register_user()的成功回調,並用它在我發送給POST請求的JSON響應。

但在迴應我得到只有這

{name: 'hello'}

有什麼辦法來調試尤其是register_user()回調部分?

回答

1

Twilio開發者傳道這裏。

我看到你已經在your answer中解決了這個問題,但是我只想解釋發生了什麼以及爲什麼這是你的解決方案。

在你原來的代碼:

app.post('/forTwilio', function(req, res){ 
    authy.register_user('[email protected]', '8753565612', '91', function(err, res){ 
     authyUsrId = 'world'; 
    }); 
    res.json({name: 'hello', msg: authyUsrId}); 
}); 

你設置你的回調從API請求Authy內authyUsrId變量。然後您嘗試在調用中使用authyUsrId以使用JSON進行響應。但是,register_user是一個異步調用,因此它下面的代碼在回調內運行的代碼之前運行。實際上,reguster_user函數必須發出HTTP請求,所以只有在請求完成後纔會運行回調。

如果添加登錄到您的原代碼,就像這樣:

app.post('/forTwilio', function(req, res){ 
    authy.register_user('[email protected]', '8753565612', '91', function(err, res){ 
     console.log("Received response from Authy"); 
     authyUsrId = 'world'; 
    }); 
    console.log("Sending JSON response"); 
    res.json({name: 'hello', msg: authyUsrId}); 
}); 

你會看到你的日誌:

Sending JSON response 
Received response from Authy 

你的修復是爲了迴應你的回調中原來的Web請求,當你有你需要的所有數據。這就是它工作的原因。如果我正在更新您的原始代碼,它現在看起來像:

app.post('/forTwilio', function(req, res){ 
    authy.register_user('[email protected]', '8753565612', '91', function(err, res){ 
     authyUsrId = 'world'; 
     res.json({name: 'hello', msg: authyUsrId}); 
    }); 
}); 

希望這是有道理的。

+0

謝謝@philnash。這真的很有幫助。 – somnathbm

0

我解決了它。直接從register_user()作品的成功回調中發送回覆。

app.post('/forTwilio', function(req, res){ 

    // send the received data to Twilio Authy 
    authy.register_user('[email protected]', '9224753123', '91', function(err, res2){ 
     res.send(res2.user); 
    }); 
});