AngularJS feature for dispatching Twilio SMS notifications

After some experimentation, I have developed an AngularJS service that can be utilized by the controller to send text messages triggered by specific events in the application. The core of this implementation is based on this solution, and here is how it operates:

To begin with, let's take a look at the service itself:

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

    }

  }

}

Next, we need to configure it in the controller:

function ConsumerBusinessProfileCtrl($scope, BusinessService) {

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

}

Lastly, we invoke it from the view:

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

I have successfully tested the jsfiddle demo using my own credentials and phone numbers, and it functions perfectly. However, when implementing it, I encounter a 401 (UNAUTHORIZED) error. I suspect that this issue may arise because $http does not support beforeSend or afterSend. Can someone assist me in resolving this dilemma?

Answer №1

Revised the $http code snippet to resolve the issue:

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

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is forwardRef not explicitly exported by React?

UPDATE: The issue with the code implementation below has been resolved. It was discovered that the error was caused by a react-redux upgrade, as redux now requires functional components instead of class components. import React, { forwardRef } from ' ...

Invoke a function from a popup window, then proceed to close the popup window and refresh the parent page

When a link in the parent window is clicked, it opens a child window. Now, when the save button is clicked in the child window, I need to trigger a Struts action, close the child window, and reload the parent window. function closeChildWindow(){ document. ...

Managing an unexpected variable when making an AJAX request

Here is a code snippet that I am working with: var User = { get: function (options) { var self = this; $.ajax({ url: options.url, success: function (data, response) { self.nextPageUrl = data.pagination.next_page; opt ...

Is there a way to postpone the mouseover event for vertical tabs?

While this may seem like a simple question to some, my programming skills are not quite up to par. I am seeking help from someone who can assist me. My goal is to delay the mouseover event on vertical tabs so that users can jump directly from tab 1 to ta ...

What is the location within an object3d where I can access the dynamic point coordinates?

Watching one singular point rotate around the Y axis is quite intriguing. I am eager to witness the shift in X coordinate as it moves along its trajectory. Although the starting point remains unchanged, I wonder where the dynamic coordinates lie. Cou ...

React cannot be utilized directly within HTML code

I am looking to incorporate React directly into my HTML without the need for setting up a dedicated React environment. While I can see the test suite in the browser, my React app fails to load. Below is the content of my script.js file: I have commented ...

Only dispatch to props upon being clicked

I am encountering an issue with the mapDispatchToProps function being sent as a whole, rather than only when I click on the delete button. My class successfully fetches the list data and everything works as expected. However, upon adding the delete button ...

Why do certain URLs bypass the filters despite not meeting the criteria in the Chrome extension?

I am currently developing a Chrome extension that is designed to automatically close tabs when specific URLs are visited, helping me stay focused and avoid distractions. The list of sites that should trigger tab closures includes: YouTube Facebook Reddit ...

Can we enhance the efficiency of this equation?

The formula provided organizes the elements in the container based on mouse movement. The issue stemmed from the image size and the different calculations performed when approaching along the x and y axes from various directions. const zoomEffect = (even ...

Display loading spinner in Material-UI Table while fetching data

Is it possible to display a Circular progress indicator while waiting for data to populate the table? How can this be accomplished? Currently, the table shows No records to display until the data is retrieved from the server. https://i.stack.imgur.com/Ljq ...

Learn how to use Cocos2d 2.1.4 to load text, strings, and JSON in HTML

Struggling to upload a large string to my project to use as a matrix, I've run into issues trying to load a text file or json into my HTML5 project. While I've seen it can be done in 3.0 using cocos2d, I'm wondering if there's a way to ...

Preventing React callback refs from exposing class methods externally

In the task at hand, I am required to create a React component for displaying toasts that hide by themselves and show from outside. Most guides on React focus on how to access the DOM from a React component, but there is little information available on how ...

Utilizing highcharts to visualize non-linear time data pulled from a CSV file

I am seeking guidance on implementing a simple graph based on data from a CSV file in web development. I lack experience in this area and have struggled to find a suitable example to follow. The CSV file contains data in the format of a unix timestamp, hu ...

What is the reason for the malfunction of native one-time binding when using the `::` expression in Angular version 1.3.5?

I am having an issue with AngularJS's one-time binding feature using the :: expression. Despite my code setup, the values are still changing. I must be missing something crucial here. Consider this controller: $scope.name = "Some Name"; $scope.chang ...

What causes addEventListener to not return a value?

In this snippet of code: let rockClick = rockBtn.addEventListener('click', playRound.bind("rock", computerPlay(), false)); After using console.log(), the output is undefined. The purpose of rockBtn:const rockBtn = document.querySelecto ...

How can the parameters for a cube geometry in three.js be dynamically updated?

Wondering about something here. I noticed that Three.js geometries come with 'parameter' fields associated with them. Take, for example, the box geometry shown in the image below... box Geometry parameters I attempted to update these parameters ...

What is the best way for me to implement a .config feature to allow for customization of my

I have developed a small code library for angular js. Within my library's main module, I have implemented a method called .config that relies on my moduleConfigProvider. I anticipate the user of my library to invoke .configure on my config provider du ...

Extract the TypeScript source code to find the interface associated with a specific React component

Is there a way to access props from a React class declared in an interface associated with that class? Here's an example of the code: interface SomeProps { text: string; label?: string; } class SomeClass extends React.Component<SomeProps& ...

Javascript closure struggles to identify global variables

Recently attempted to conduct end-to-end testing on the UI using Testcafe. The script below is designed to accept user input and evaluate it during runtime to assist in creating new test scripts. Unfortunately, it seems to be failing to recognize 'Sel ...

I need to extract particular information from a JSON file and include it in another JSON file or variable

Hey there, I'm looking to retrieve specific data from an API and store it in a file. The API I am interested in is quite large, so I only want to extract certain information for each item, such as the 7-day price. However, when I attempt to use an emp ...