Using Pastebin API in Node.js

I've been trying to post a paste to Pastebin in Node.js, but it appears that I'm doing it wrong.

I'm getting a Bad API request, invalid api_option, however I'm clearly setting the api_option to paste like the documentation asks for.

var http = require('http');
var qs = require('qs');

var query = qs.stringify({
  api_option: 'paste',
  api_dev_key: 'xxxxxxxxxxxx',
  api_paste_code: 'Awesome paste content',
  api_paste_name: 'Awesome paste name',
  api_paste_private: 1,
  api_paste_expire_date: '1D'
});

var req = http.request({
  host: 'pastebin.com',
  port: 80,
  path: '/api/api_post.php',
  method: 'POST',
  headers: {
    'Content-Type': 'multipart/form-data',
    'Content-Length': query.length
  }
}, function(res) {
  var data = '';
  res.on('data', function(chunk) {
    data += chunk;
  });
  res.on('end', function() {
    console.log(data);
  });
});

req.write(query);
req.end();

console.log(query) confirms that the string is well encoded and that api_option is there and set to paste.

Now, I've been searching forever on possible causes. I also tried setting the encoding on the write req.write(query, 'utf8') because the Pastebin API mentions that the POST must be UTF-8 encoded. I rewrote the thing over and over and re-consulted the Node HTTP documentation many times.

I'm pretty sure I completely missed something here, because I don't see how this could fail. Does anyone have an idea of what I have done wrong?

What you're creating isn't a properly-formed multipart/form-data request; it looks more like an application/x-www-form-urlencoded request. From what I can tell about pastebin's API (I've never actually used it) the latter is what you really want, so try changing the Content-Type to it.

It does not answer directly your question but maybe it could help...

Have you try to use the request module ?

Your example would be much easier to read and you might find the problem...

mikeal/request