Using WinJS.xhr to POST

Tags: win8 winjs twilio rest

In the process of building a Windows 8 Twilio app, I ran head first into an issue using WinJS.xhr to send POST requests. The official documentation is pretty thin, so I thought I'd write-up how to accomplish this here.

Using WinJS.xhr in general is quite nice. It abstracts away all the nonesense of XMLHttpRequest and provides a simple interface that uses Promises to handle the asynchronous responses. Here's a simple example that uses the Twilio REST API to retrieve a list of SMS messages from a user's account:

  user: accountSid, password: authKey, 
  url: "" + accountSid + "/SMS/Messages.json"
  function (success) {
  function (error) {

Obviously, the example would be much shorter if I wasn't using HTTP BASIC auth and had defined some named functions for the callback. But hey, pretty simple! Anyway, what if you want to do a POST? We'll here's what won't work:

  type: "post", user: accountSid, password: authKey, 
  url: "" + accountSid + "/Calls.json",
  data: dataString
}).then(success, error);

You'll notice I defined type: "post" to indicate that I want to POST. But, it turns out this is not enough. The answer to getting this to work is to manually set the response header. Here's some code that does work:

  type: "post", user: accountSid, password: authKey, 
  url: "" + accountSid + "/Calls.json",
  headers: { "Content-type": "application/x-www-form-urlencoded" },
  data: dataStr
    }).then(success, error);

That's it. Just make sure to set:

headers: { "Content-type": "application/x-www-form-urlencoded" }

..and you're good to go!

About Me

Hey there. My name is Carter Rabasa and I am a husband and father of two beautiful daughters Catherine and Emily. I live in Seattle, WA.