Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make request in NodeJs server?

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 ?

like image 770
Royi Namir Avatar asked Jul 21 '26 17:07

Royi Namir


1 Answers

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

like image 117
Alex K Avatar answered Jul 24 '26 07:07

Alex K



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!