【问题标题】:Twilio Authy Callback issueTwilio Authy 回调问题
【发布时间】:2016-10-22 09:57:27
【问题描述】:

我不确定 Twilio Authy 的 register_user() 的成功回调是否触发。在我的代码中

var authyUsrId;
//global.authyUsrId;

app.post('/forTwilio', function(req, res){
    // send the received data to Twilio Authy
    authy.register_user('maverick@example.com', '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() 回调部分?

【问题讨论】:

    标签: javascript node.js express twilio authy


    【解决方案1】:

    这里是 Twilio 开发者宣传员。

    我看到你在your answer 中解决了这个问题,但我只是想解释一下发生了什么以及为什么这是你的解决方案。

    在您的原始代码中:

    app.post('/forTwilio', function(req, res){
        authy.register_user('maverick@example.com', '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('maverick@example.com', '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
    

    当您拥有所需的所有数据时,您的解决方法是在回调中响应您的原始网络请求。这就是它起作用的原因。如果我正在更新您的原始代码,它现在看起来像:

    app.post('/forTwilio', function(req, res){
        authy.register_user('maverick@example.com', '8753565612', '91', function(err, res){
            authyUsrId = 'world';  
            res.json({name: 'hello', msg: authyUsrId});
        });
    });
    

    希望这是有道理的。

    【讨论】:

      【解决方案2】:

      我解决了。直接从register_user() 的成功回调发送响应。

      app.post('/forTwilio', function(req, res){
      
          // send the received data to Twilio Authy
          authy.register_user('jimmy@example.com', '9224753123', '91', function(err, res2){
              res.send(res2.user);
          });
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-08-21
        • 2021-10-31
        • 1970-01-01
        • 1970-01-01
        • 2017-03-25
        • 2020-01-31
        • 1970-01-01
        相关资源
        最近更新 更多