Making a POST with node.js

Submitted by aaron on Thu, 03/31/2011 - 10:55

There are a lot of articles out there on how to do a POST with node.js.  I couldn't get any of them to work right, so here is what I came up with:

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

var post_domain = 'localhost';
var post_port = 80;
var post_path = '/post_demo.php';

var post_data = querystring.stringify({
  'your' : 'post',
  'data': 'goes here!'
});

var post_options = {
  host: post_domain,
  port: post_port,
  path: post_path,
  method: 'POST',
  headers: {
    'Content-Type': 'application/x-www-form-urlencoded',
    'Content-Length': post_data.length
  }
};

var post_req = http.request(post_options, function(res) {
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('Response: ' + chunk);
  });
});

// write parameters to post body
post_req.write(post_data);
post_req.end();

 

Copyright © 2011, Aaron Blondeau

Drupal theme by Kiwi Themes.