Make request in NodeJs server?

Problem

I've created a server http listener :

var http = require('http');
http.createServer(function (req, res)
{
        res.writeHead(200,
        {
                'Content-Type': 'text/plain'
        });
        res.write('aaa');
        res.end();
}).listen(1337, '127.0.0.1');
console.log('waiting......');

it is working find and do response.

enter image description here

Now , I want - foreach client request - The server to perform another request and append a string "XXX" :

So I wrote :

var http = require('http');
var options = {
        host: 'www.random.org',
        path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
http.createServer(function (req, res)
{
        res.writeHead(200,
        {
                'Content-Type': 'text/plain'
        });
        res.write('aaa');

        http.request(options, function (r)
        {
                r.on('data', function (chunk)
                {
                        res.write('XXX');
                });
                r.on('end', function ()
                {
                        console.log(str);
                });
                res.end();
        });

        res.end();
}).listen(1337, '127.0.0.1');
console.log('waiting......');

So now foreach request , it should write : aaaXXX ( aaa+XXX)

But it doesnt work . it still egenrated the same output.

What am I dong wrong ?

Problem courtesy of: Royi Namir

Solution

Try this:

var http = require('http');
var options = {
        host: 'www.random.org',
        path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};
http.createServer(function (req, res)
{
        res.writeHead(200,
        {
                'Content-Type': 'text/plain'
        });
        res.write('aaa');

        var httpreq = http.request(options, function (r)
        {
            r.setEncoding('utf8');
            r.on('data', function (chunk)
            {
                res.write(' - '+chunk+' - ');
            });
            r.on('end', function (str)
            {
                res.end();
            });

        });

        httpreq.end();

}).listen(1337, '127.0.0.1');
console.log('waiting......');

Also, worth reading this article on nodejitsu

Solution courtesy of: Alex

Discussion

You're calling res.end() too early... you only want to do thing when EVERYTHING has been written (e.g. when r.on('end') is called).

For something like this, I would highly recommend using the excellent request library (https://github.com/mikeal/request).

This has a wonderful API, for example:

var request = require('request');
request('http://www.google.com', function (error, response, body) {
  if (!error && response.statusCode == 200) {
    console.log(body) // Print the google web page.
  }
})
Discussion courtesy of: isNaN1247

This recipe can be found in it's original form on Stack Over Flow.