lache
lache

Reputation: 830

How to remove CORS error from svelte Twilio API?

My goal is to send a text in my app. I have hosted at netlify, but also had on localhost:5000, neither worked. I am using svelte and twilio. I am getting the following error:

Access to fetch at 'https://svelte-service-xxxx.twil.io/sms' from origin 'https://xxxxxxx.netlify.app' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. If an opaque response serves your needs, set the request's mode to 'no-cors' to fetch the resource with CORS disabled.

I am using the serverless function in the tutorial and copied all that code. I can't find anything on it? How do i get around this CORS thing?

The tutorial: https://www.twilio.com/blog/send-sms-svelte-twilio-functions Tried this:No 'Access-Control-Allow-Origin' header is present on the requested resource—when trying to get data from a REST API

MYSVELTE

<script>
  const handleText = async () => {
    const response = await fetch("https://svelte-service-xxxx.twil.io/sms");
    const data = await response.json();
    console.log(data);
    status = data.status;
  };
</script>

MY FUNCTION IN TWILIO (according to the tutorial)

export async function handler(context, event, callback) {
  const twilioClient = context.getTwilioClient();
  
  const messageDetails = {
    body: "Ahoy, Svelte developer!",
    to: "+xxxxxxxxxx",
    from: "+xxxxxxxxxx"
  }
  
  const response = new Twilio.Response();
  
  const headers = {
    "Access-Control-Allow-Origin": "https://xxxxx.netlify.app/",
    "Access-Control-Allow-Methods": "GET,PUT,POST,DELETE,OPTIONS",
    "Access-Control-Allow-Headers": "Content-Type", <<----?????
    "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);
  }
}

Upvotes: 1

Views: 3700

Answers (1)

philnash
philnash

Reputation: 73027

There are two issues here. First up, you changed the export to ES modules, which is currently unsupported by Twilio Functions. So you have:

export async function handler(context, event, callback) {

but it should be:

exports.handler = async function (context, event, callback) {

You were seeing a CORS issue here to start with because the response from a Twilio Function when it is broken does not include CORS headers. However, you do still have a CORS issue.

When a browser sends the Origin header, it does so without a trailing slash. That Origin has to match the URL in the Access-Control-Allow-Origin header. So you need to change the header to drop the trailing slash:

    "Access-Control-Allow-Origin": "https://xxxxx.netlify.app",

Upvotes: 3

Related Questions