I ran into an annoying problem with the popular npm request library when trying to send Protocol Buffers to my backend API.

More specifically, I'm trying to send a Content-Type of

application/x-protobuf  

with an array of bytes as the body.

Using Mikeal's 'request', I keep running into the following cryptic error:

Argument error, options.body.  

It seems like the Content-Length HTTP header was not being set correctly. After perusing the request documentation and stumbling upon this StackOverflow post, I realized that request only supports body types of Array, Buffer, or String. The Buffer type in question here is only designed for use on the server-side, so when used in conjunction with the ProtoBuf.js library I'm using on the client-side, the body was unable to be converted properly when sending over the wire.

I experimented with a few different HTTP request libraries, and instead of going with any HTTP-request based libraries, I found a way around my problems by opting for using an isomorphic fetch polyfill.

Using CommonJS, all you need to do is

require('es6-promise').polyfill();  
require('isomorphic-fetch');

// This returns a promise
fetch('POST_URL_HERE', {  
  method: 'post',
  headers: 'application/x-protobuf',
  body: ProtoBufObject.toArrayBuffer()
});

Also, if you haven't noticed... I recently added code syntax highlighting to my blog. ^_^