2016-01-23 185 views
0

這是在我的頭撞在屏幕上半天后,所以任何幫助將不勝感激。通過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。 –

回答

0

嘿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對我有幫助嗎?如果是這樣,請將其標記爲正確答案並在此發佈新問題。 –