Home > front end >  send a text from svelte app to twilio function
send a text from svelte app to twilio function

Time:03-25

Still can't figure out this Cors thing its pretty annoying. Trying to test sending a text from an input to twilio. I want to text from my phone to a dynamic number. I keep getting cors error no matter what i do? I am definitely doing something wrong, am i not allowed to send from local host?

SVELTE APP

let phoneNumber = "";

const handleSendText = () => {
    fetch("https://svelte-service-9106.twil.io/sms", {
      method: "POST",
      body: JSON.stringify({
        to: phoneNumber,
        from: " 11111111111",
      }),
      headers: {
        "Content-Type": "application/json",
      },
    })
      .then((response) => {
        if (!response.ok) {
          throw new Error("failed");
        }
      })
      .catch((err) => {
        console.log(err);
      });
  };
 <input type="text" bind:value={phoneNumber} />
 <button on:click={handleSendText}>Send</button>

TWILIO FUNCTION

exports.handler = async function (context, event, callback){
  const twilioClient = context.getTwilioClient();
  
  const messageDetails = {
    body: "Ahoy, Svelte developer!",
    to: event.to,
    from: event.from,
  }
  
  const response = new Twilio.Response();
  
  const headers = {
    "Access-Control-Allow-Origin" : "http://localhost:5000",
    "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,OPTIONS",
    "Content-Type": "application/json"
  };
        
  response.setHeaders(headers);
  
  try {
    const message = await twilioClient.messages.create(messageDetails);
    response.setBody({
      status: `Your message was sent successfully with SID: ${message.sid}`
    });
    return callback(null, response);
  } catch(error) {
    response.setBody({
      status: error
    });
    return callback(response);
  }
}

ERROR enter image description here

CodePudding user response:

I just copied your Function, deployed it to my own Twilio account and was able to make successful fetch requests to it from localhost:5000.

However, if I caused an error by, for example, using an incorrect from number, then I got the CORS error. The issue is that your Function is returning the response object as the first argument to the callback function. That argument is reserved for error objects, not for responses, and Twilio Functions will create its own response when it receives an error as the first argument to the callback function. That response does not include CORS headers, so you get the CORS error.

The way to deal with this is to send your response and set the status code on it yourself.

So, update your Function to:

  try {
    const message = await twilioClient.messages.create(messageDetails);
    response.setBody({
      status: `Your message was sent successfully with SID: ${message.sid}`
    });
    return callback(null, response);
  } catch(error) {
    response.setBody({
      status: error.message
    });
    response.setStatusCode(400);
    return callback(null, response);
  }

You can see that in the catch block I am setting the status code to 400 and returning the response object as the second argument to the callback.

Now, your front-end code is also not exposing the error that you would get back from this, mainly because it throws its own exception when the response is not correct. Try updating to parse the body of the error and throw an error using the status property that you set in the error.

fetch("https://svelte-service-9106.twil.io/sms", {
  method: "POST",
  body: JSON.stringify({
    to: phoneNumber,
    from: " 111111111111",
  }),
  headers: {
    "Content-Type": "application/json",
  },
})
  .then((response) => {
    if (!response.ok) {
      response.json().then((body) => { 
        throw new Error(body.status);
      })
    } else {
    console.log("Success"); }
  })
  .catch((err) => {
    console.log(err);
  });
  

Once you update like this you will still get an error, but the error will contain the error message from the API and you will be able to fix that.

  • Related