【问题标题】:node js twilio send sms doesn't work节点js twilio发送短信不起作用
【发布时间】:2017-07-02 18:42:24
【问题描述】:

我有这个功能发送短信

 var twiml = new MessagingResponse();

function sendsms() {
                  twiml.message("aaa");
                 console.log(twiml.toString());
                   }

但是当我在 User.findone 中调用这个函数时

 User.findOne({}, function(err, user) {
                 if (condition) {
                     sendsms();
                 }
             })

它成功记录了 twiml.toString 但没有发送短信 当我在 user.findOne 外部调用时,短信发送成功

sendsms()

这是发送短信的路径

router.post('/sendSMS', function(req, res) {
    var phone = req.body.phone;



    User.findOne({}, function(err, user) {


            require('../config/sendSMS')(user, phone);

            res.status(200).json({ success: true, message: 'message sent successfully' });

        }

    });

这是获取和重播短信的途径

router.post('/getSMS', function(req, res) {

    require('../config/getAndReplay')(req, res);

});

【问题讨论】:

  • 你能分享更多不起作用的代码吗?当你说“我在 User.findone 中调用这个函数时它不起作用”你是怎么称呼它的?你能显示代码吗?
  • 我假设这是在快速应用程序或类似应用程序中响应传入请求的代码。你能分享整个路线/动作吗?
  • 我确实添加了路线/动作,非常感谢
  • 好的,../config/sendSMS../config/getAndReplay 里面是什么?
  • 发送工作正常 getandreplay 包含在我的控制台顶部的代码,当调用 user.findone 它成功记录 twimltostring 但是当调用 sendms 外部用户时不发送短信.findone 成功并成功发送短信

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


【解决方案1】:

这里是 Twilio 开发者宣传员。

您的代码中的问题是您混合了同步和异步代码。

User.findOne 是一个异步调用,因此在结果回调中调用getandreplay() 函数意味着它会在您的路由中完成响应之后发生。

我的建议是你 return 你想从 getandreplay() 回复的消息,并使用它来形成对传入请求的响应。像这样:

function getandreplay(node) {
    if (node.outs.length > 0) {
        if (node.outs.includes(req.body.Body.toLowerCase())) {
            for (var i = 0; i < node.output.length; i++) {
                var el = node.output[i];
                if (req.body.Body.toLowerCase() == el[0]) {
                    req.session.lastnode = getnode(el[1]);
                    if (getnode(el[1]).outs.length == 0) {
                        req.session.destroy();
                        User.findOneAndUpdate({}, { $push: { users: userPhone } }, { safe: true, upsert: true }, function(user, err) {});
                    }
                    return getnode(el[1]).msg;
                }
            }
        } else {
            return node.msg
        }
    }
}

然后,当您调用User.findOne() 时,您会从getandreplay() 获得结果并将其作为响应发回:

User.findOne({}, function(err, user) {
    if (!user.users.includes(userPhone)) {
        twiml.message(getandreplay(mynode));
    }
    res.writeHead(200, { 'Content-Type': 'text/xml' });
    res.end(twiml.toString());
});

请注意,这里我在 User.findOne() 的回调函数中调用 res.end

让我知道这是否有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-08
    相关资源
    最近更新 更多