gpt4 book ai didi

javascript - 用于发送 Twilio SMS 消息的 AngularJS 服务

转载 作者:行者123 更新时间:2023-12-02 14:33:40 24 4
gpt4 key购买 nike

我一直在尝试创建一个 AngularJS 服务,该服务可以从 Controller 调用并根据应用程序中的特定事件发送文本消息。该实现基于 this ,工作原理如下:

首先,我们有服务:

function BusinessService($http) {

this.twilioSMS = {

sendMessage: function(to, from, body) {

var accountSid = 'xxx';
var authToken = 'xxx';

var testEndpoint = 'https://api.twilio.com/2010-04-01/Accounts/' + accountSid + '/SMS/Messages.json';
var liveEndpoint = 'https://api.twilio.com/2010-04-01/Accounts/' + accountSid + '/Messages.json';

var data = {
To: to,
From: from,
Body: body
};

$http({
method: 'POST',
url: testEndpoint,
data: data,
dataType: 'json',
contentType: 'application/x-www-form-urlencoded',
beforeSend: function(xhr) {
xhr.setRequestHeader("Authorization",
"Basic " + btoa(accountSid + ":" + authToken) // !
);
},
success: function(data) {
console.log("Got response: %o", data);
if (typeof successCallback == 'function')
successCallback(data);
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("Request failed: " + textStatus + ", " + errorThrown);
if (typeof failCallback == 'function')
failCallback(jqXHR, textStatus, errorThrown);
}
})

}

}

}

然后在 Controller 中进行设置:

function ConsumerBusinessProfileCtrl($scope, BusinessService) {

$scope.sendMessage = function(to, from, body) {
return BusinessService.twilioSMS.sendMessage(to, from, body)
}

}

然后从 View 中调用它:

<a ng-click="sendMessage('+12345678901', '+15005550006', 'Hey Jenny! Good luck on the bar exam!')">Send Message</a>

我已经使用我的 accountSid、authToken 和电话号码测试了 jsfiddle example,它工作正常。但我的实现失败并出现 401 (UNAUTHORIZED) 错误。我的一部分认为这是因为 $http 不支持 beforeSendafterSend。但我不确定?这里有人能指导我正确的方向吗?

最佳答案

将 $http 更改为以下内容以修复问题:

 $http({
method: 'POST',
url: testEndpoint,
data: data,
transformRequest: function(obj) {
var str = [];
for (var p in obj)
str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
return str.join("&");
},
headers: {
'Authorization': 'Basic ' + btoa(accountSid + ':' + authToken),
'Content-Type': 'application/x-www-form-urlencoded'
},
}).success(function(response) {
console.log(response);
}).error(function(error) {
console.log(error);
});
}

关于javascript - 用于发送 Twilio SMS 消息的 AngularJS 服务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37631619/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com