【问题标题】:TypeError: Cannot read property 'Digits' of undefined in twilio when gathering user input from callTypeError:从调用中收集用户输入时,无法读取 twilio 中未定义的属性“数字”
【发布时间】:2024-05-23 12:50:01
【问题描述】:

我使用了Gather User Input via Keypad (DTMF Tones) in Node.js twilio 文档中的代码 用于从调用中获取用户输入。

    app.post('/voice', (request, response) => {
       const twiml = new VoiceResponse();

       function gather() {
         const gatherNode = twiml.gather({ numDigits: 1 });
         gatherNode.say('For sales, press 1. For support, press 2.');
         twiml.redirect('/voice');
       }
       if (request.body.Digits) {
         switch (request.body.Digits) {
         case '1':
           twiml.say('You selected sales. Good for you!');
           break;
         case '2':
           twiml.say('You need support. We will help!');
           break;
         default:
           twiml.say("Sorry, I don't understand that choice.").pause();
           gather();
           break;
        }
      } else {
    gather();
   }

  response.type('text/xml');
  response.send(twiml.toString());
  });

当我拨打我的 twilio 号码时,我在 if 语句中收到类似“TypeError: Cannot read property 'Digits' of undefined”的错误。我想获取用户在通话过程中输入的号码。提前致谢!

【问题讨论】:

  • 感谢您的快速响应。它现在工作正常。问题出在我的服务提供商呼叫 twilio 号码。我改变了我的服务现在工作正常:)

标签: javascript node.js twilio twilio-api twilio-twiml


【解决方案1】:

您最初的 request 似乎没有 body 属性。 尝试在您的 if 声明中添加支票:

if (request.body && request.body.Digits) {
  // switch / case
} else {
  gather();
}

【讨论】:

    【解决方案2】:

    记录请求的值并检查这些属性, 注释掉以下所有内容:if(request.body.Digits)

    然后在它的位置运行它:

    console.log(request)
    

    因为错误告诉您该对象中未定义主体。 否则,如果它存在,则在此

    中封装switch语句
    if(request.body)
    {
    //Switch statement
    }
    

    【讨论】:

      【解决方案3】:

      我只是遇到了同样的问题。添加这两行为我修复了它:

      const urlencoded = require('body-parser').urlencoded;
      app.use(urlencoded({ extended: false }));
      

      它们也在 Twilio 文档中。我是 Node 的新手,所以我不确定为什么没有它们代码会中断。根据 Twilio 提供的评论, // Parse incoming POST params with Express middleware

      【讨论】:

        最近更新 更多