0
votes

Novice Dev...

I have an Ionic/Angular app with a form group for a person to input their details and when they Sign In I am trying to send an SMS via Twilio's API using POST.

If I add the login details to the API url I receive the following error: Failed to execute 'fetch' on 'Window': Request cannot be constructed from a URL that includes credentials: https://XXX:[email protected]/2010-04-01/Accounts/XXX/Messages.json

And If I add the credentials in the header I receive the below: POST https://api.twilio.com/2010-04-01/Accounts/XXX/Messages.json 401 (Unauthorized)

I am not concerned about the key being hardcoded as this is an internal app but not sure how to successfully implement the SMS functionality.

Below is my .ts code for the function.

Any Suggestions?

  signIn(form){
  fetch('https://api.twilio.com/2010-04-01/Accounts/xxx/Messages.json',{
    method: 'POST',
    headers: {
      'Accept': 'application/json',
      'Content-Type': 'application/json',
      'Authorization': 'Basic ' + btoa('xxx:xxx'),
    },
    body: JSON.stringify({
      "from": ["+xxxxx"],
      "to": ["+xxxxx"],
      "body": this.contractor.firstName + " " + this.contractor.lastName,

    })
  }).then(function(response) {
  return response.json();
  });
1
I suggest you work on getting the bearer token set in a test harness first. The way you are trying to do it throws an error because it's restricted due to security concerns. nicolaswidart.com/blog/… - E. Maggini

1 Answers

0
votes
Try this solution
 async fetchData(token) {
//token can be hardcoded or passed
    console.log("inside asycn "+token);
  
      let headers = new HttpHeaders()
      .set('content-type','application/json')
      .set('Access-Control-Allow-Origin', '*')
      .set( "Authorization" , "Bearer "+token)
      const httpOptions = {
         headers: headers
       };

     this.message = "Fetching..";
      this.response = "";
      this.response = await this.http
     
      .get<void>('https://urlofyourendpoint',httpOptions)
        .pipe(delay(1000))
        .subscribe (x=>{console.log(x);})
      this.message = "Fetched";
    }