Updating post http request length in node.js

I'm using node.js to post a http request. the code works with if i define my post data ahead of the 'options' field, but if I initially set my post_data string to empty and update it later it doesn't pick up the new length. How would I get it to do that ? I'm looking to send multiple posts of varying lengths to the same place in a loop so need to be able to do this.

var post_data=''; //if i set my string content here rather than later on it works

var options = {
        host: '127.0.0.1',
        port: 8529,
        path: '/_api/cursor',
        method: 'POST',
        headers: {
            'Content-Type': 'application/json',
            'Content-Length': post_data.length
        }
    };

    var req = http.request(options, function(res) {
        res.setEncoding('utf8');
        res.on('data', function (chunk) {
            console.log('BODY: ' + chunk);
        });
    });

    req.on('error', function(e) {
        console.log('problem with request: ' + e.message);
    });

   post_data = 'a variable length string goes here';//the change in length to post_data is not                     //recognised    
   req.write(post_data);
   req.end();        

'Content-Length': post_data.length

You ran this before setting post_data.

If you want to set post_data after creating the object, you'll need to set it manually later:

options.headers['Content-Length'] = post_data.length;

Note that you must set that before calling http.request().

Posting data is a matter of sending a query string (just like the way you would send it with an URL after the ?) as the request body.

This also requires to declare Content-Type and Content-Length values so the server knows how to interpret the data.

var querystring = require('querystring');

var data = querystring.stringify({
      username: yourUsernameValue,
      password: yourPasswordValue
    });

var options = {
    host: 'my.url',
    port: 80,
    path: '/login',
    method: 'POST',
    headers: {
        'Content-Type': 'application/x-www-form-urlencoded',
        'Content-Length': data.length
    }
};

var req = http.request(options, function(res) {
    res.setEncoding('utf8');
    res.on('data', function (chunk) {
        console.log("body: " + chunk);
    });
});

req.write(data);
req.end();

You need to replace:

'Content-Length': post_data.length

for:

'Content-Length': Buffer.byteLength(post_data, 'utf-8')

See https://github.com/strongloop/express/issues/1870