Small Lesson on Using Request in node.js with Form-data

I was playing around with 46elks.com api for sending SMS (it’s a Swedish Twilio). Trying to send data using request I got 404 Not Found all the time. Using something like below.

var reqeustOptions = {
  uri: urljoin(apiBaseUrl, apiBasePath, ‘SMS’),
  method: ‘POST’,
  auth: {
    user: ‘username’,
    pass: ‘pwd’
  },
  formData: {
    from: fromNubmer,
    to: toNumber,
    message: message
  }
};

request(reqeustOptions);

Notice the formData. That infers that the form type will be multipart/form-data which did not work at all with the 46elks api. All I got was 404 Not Found all the time.

After trail and error in Postman (chrome plugin for building HTTP requests). So here’s the thing if you use form instead. The form-data type inferred is x-www-form-urlencoded. When I changed it (after 4 hours of head-banging-against-the-wall) to:

var reqeustOptions = {
  uri: urljoin(apiBaseUrl, apiBasePath, ‘SMS’),
  method: ‘POST’,
  auth: {
    user: ‘username’,
    pass: ‘pwd’
  },
  form: {
    from: fromNubmer,
    to: toNumber,
    message: message
  }
};

request(reqeustOptions);

It worked like a charm! 🙂

I googled like crazy before figuring this out, hopefully you stumbles upon this post if you have the same problem.

Kommentera

E-postadressen publiceras inte. Obligatoriska fält är märkta *