twiliocloudflaretwilio-apicloudflare-workerstwilio-javascript

POST request errors out when CURL works


I’m trying to use a cloudflare worker (Pasted below) to send an SMS message via the Twilio API. The CURL request (also pasted below) I’m basing the worker off of works.

Based on the 400 error from the worker the message body isn’t passed in correctly {"code": 21602, "message": "Message body is required.", "more_info": "https://www.twilio.com/docs/errors/21602", "status": 400}

but the code looks fine to me. We can at least confirm the header is passed correctly because messing with the authorization value changes the error.

I also looked at the example POST request in the template gallery and can’t see a reason for the failure. https://developers.cloudflare.com/workers/templates/pages/post_json/

What do i need to change in my worker code to make the POST request work?

Note: i recognize i shouldn’t put the Twilio Auth token in the body but I’ll rotate the key later.

async function handleRequest(request) {
  const init = {
    body: JSON.stringify(body),
    method: 'POST',
    headers: {
      'content-type': 'application/json',
      'Authorization': "Basic " + btoa('[account id]:[Authtoken]'),
    },
  }

  return await fetch(url, init)
}

addEventListener('fetch', event => {
  return event.respondWith(handleRequest(event.request))
})

const url = 'https://api.twilio.com/2010-04-01/Accounts/[Account id]/Messages.json'
const body = {
  Body:"Hello World",
  From:"+[some number]",
  To:"+[some number]]",
}
curl 'https://api.twilio.com/2010-04-01/Accounts/[Account id]/Messages.json' -X POST \
--data-urlencode 'To=+[some number]' \
--data-urlencode 'From=+[some number]' \
--data-urlencode 'Body=Hello World' \
-u [account id]:[auth token]

Solution

  • because Twilio requires application/x-www-form-urlencoded.

    REST API: Your Request

    Creating or updating a resource involves performing an HTTP PUT or HTTP POST to a resource URI. In the PUT or POST, you represent the properties of the object you wish to update as form urlencoded key/value pairs. Don't worry, this is already the way browsers encode POSTs by default. But be sure to set the HTTP Content-Type header to "application/x-www-form-urlencoded" for your requests if you are writing your own client.