通过Twilio发送短信POST错误

问题描述:

这是在我的头撞在屏幕上半天后,所以任何帮助将不胜感激。通过Twilio发送短信POST错误

我正试图通过Twillio发送一条SMS消息,发送点击事件。我使用Angular,在点击时调用SendTestMessage函数。不幸的是,我一直运行到这个错误:

POST http://localhost:3000/sendsms 500 (Internal Server Error) 

这里是我的控制器:

.controller('WhotoMessageCtrl', function($scope, UserService, $http, $q){ 
    console.log("whotomessage page"); 

    $scope.saveContactInfo = saveContactInfo; 
    $scope.contact = {}; 
    $scope.sendTestMessage = sendTestMessage; 

    function sendTestMessage(number){ 
    console.log('this fired', number); 
    var defer = $q.defer(); 
    $http({ 
     url: '/sendsms', 
     method: 'POST', 
     data: JSON.stringify({number}), 
     contentType: 'application/json', 
     }).success(function (number){ 
     console.log('text has been sent to', number); 
     defer.resolve(user); 
     }); 
     return defer.promise; 
    }; 

这里是我的服务器端代码:

app.all('*', function(req, res, next) { 
    res.header("Access-Control-Allow-Origin", "*"); 
    res.header('Access-Control-Allow-Methods', 'OPTIONS,GET,POST,PUT,DELETE'); 
    res.header("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With"); 
    if ('OPTIONS' == req.method){ 
     return res.send(200); 
    } 
    next(); 
}); 

app.use(function (req, res, next) { 

var sendSMS = function(to){ 
    var outgoing = {}; 
    outgoing.to = to; 
    outgoing.from = '19725593683'; 
    outgoing.body = 'Your table is ready'; 

    client.messages.create(outgoing, function(error, message){ 
    if (error){console.log(error.message)} 
    }) 
}; 



app.post('/sendsms', function(req, res){ 
    sendResponse(res, req.body.phoneNo, 201) 
    sendSMS(req.body.phoneNo) 
    res.end(); 
}); 

有什么建议?

+0

抱歉,忽略服务器端代码中的第二个app.use。 –

嘿Twilio开发人员传道士在这里。

这可能是因为您忘记了复制代码的位,但似乎client尚未定义,这意味着您甚至没有向Twilio发出请求。

的正确方法根据the documentation初始化client是:

// Your accountSid and authToken from twilio.com/user/account 
var accountSid = '{{ account_sid }}'; 
var authToken = "{{ auth_token }}"; 
var client = require('twilio')(accountSid, authToken); 

只有这样,你可以对你的代码做:

var sendSMS = function(to){ 
    var outgoing = {}; 
    outgoing.to = to; 
    outgoing.from = '19725593683'; 
    outgoing.body = 'Your table is ready'; 

    client.messages.create(outgoing, function(error, message){ 
    if (error){console.log(error.message)} 
    }) 
}; 

希望这可以帮助你!

+0

谢谢,马科斯!我解决了这个问题,并遇到了另一个问题! –

+0

@SamuelBowler对我有帮助吗?如果是这样,请将其标记为正确答案并在此发布新问题。 –