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.

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 ?
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With