Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using node.js HTTP remote client request doesn't return any body

Tags:

node.js

I'm using node.js to download a webpage. However, it's not receiving any chunks of data:

    console.log('preparing request to ' + url)
    u = require('url').parse(url)
    var remote_client = http.createClient(80, u['host']);
    var request = remote_client.request("GET", u['pathname'], {"host": u['host']});
    console.log("request made")

    request.addListener('response', function (response) {
        response.setEncoding('binary') 
        var body = '';

        response.addListener('data', function (chunk) {
            body += chunk;
            console.log('chunk received')
        });
    });

The last console message is "request made". There are no console messages with "chunk received" or the like. Thoughts?

like image 549
Mark Avatar asked Jan 26 '11 00:01

Mark


People also ask

Do Node.js servers block on HTTP requests?

Your code is non-blocking because it uses non-blocking I/O with the request() function. This means that node. js is free to service other requests while your series of http requests is being fetched.

Does fetch work in Node?

Fetch is already available as an experimental feature in Node v17. If you're interested in trying it out before the main release, you'll need to first download and upgrade your Node. js version to 17.5.

How many HTTP requests can Node.js handle?

js can handle ~15K requests per second, and the vanilla HTTP module can handle 70K rps.

What is HTTP createServer ()?

The http. createServer() method turns your computer into an HTTP server. The http. createServer() method creates an HTTP Server object. The HTTP Server object can listen to ports on your computer and execute a function, a requestListener, each time a request is made.


1 Answers

This is an example which always worked for me:

var sys = require('sys'),
    http = require('http');

var connection = http.createClient(8080, 'localhost'),
    request = connection.request('/');

connection.addListener('error', function(connectionException){
    sys.log(connectionException);
});

request.addListener('response', function(response){
    var data = '';

    response.addListener('data', function(chunk){ 
        data += chunk; 
    });
    response.addListener('end', function(){
        // Do something with data.
    });
});

request.end();
like image 199
yojimbo87 Avatar answered Oct 13 '22 01:10

yojimbo87