通过Twilio POST错误发送短信

时间:2016-01-23 04:34:54

标签: angularjs rest post sms twilio

这是在半天敲击屏幕后出现的,所以任何帮助都会非常感激。

我试图通过Twillio在点击事件上发送短信。我正在使用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();
});

有什么建议吗?

1 个答案:

答案 0 :(得分:0)

Hey 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)}
  })
};

希望这能帮到你!