Node.js http.get example

1k views Asked by At

I've found hundreds of examples of using node.js with the http or https to make a GET, POST request. Seems easy enough.

I've created a module that returns an object. In that object, I have a function called

My functon in the restlet module:

restlet.makecall = function call() {
    console.log("This gets logged");
    http.get('http://www.google.com/', function(res) {
        console.log("statusCode: ", res.statusCode); //nothing
        console.log("headers: ", res.headers); //nothing

        res.on('data', function(d) {
            process.stdout.write(d);
            console.log("This doesn't get logged out"); //nothing
        });

    }).on('error', function(e) {
        console.error(e);
        console.log("This doesn't get logged out");
    });
    console.log("This gets logged");
};

My problem is that every time I run it, or any variation of code I've found in all the postings, NOTHING is logged out to the console...

I'm sure the problem is simple but I haven't figured it out. I'd really appreciate it if someone could point me in the right direction or even to a bit of code I could paste into that function that actually logged something out. (an error, anything!)

1

There are 1 answers

1
Stretch On

I think it's problem with your network, your callback from http.get is not being called. I would try and ping www.google.com - I suspect it won't work. Check your DNS?

I copied the code into a single .js file, and ran it, like below.

var http = require('http');

function call() {
    console.log("This gets logged");
    http.get('http://www.google.com/', function(res) {
        console.log("statusCode: ", res.statusCode); //nothing
        console.log("headers: ", res.headers); //nothing

        res.on('data', function(d) {
            process.stdout.write(d);
            console.log("This doesn't get logged out"); //nothing
        });

    }).on('error', function(e) {
        console.error(e);
        console.log("This doesn't get logged out");
    });
    console.log("This gets logged");
};

call();

I run the code with no problems, this is the output below.

This gets logged
This gets logged
statusCode:  302
headers:  { 'cache-control': 'private',
  'content-type': 'text/html; charset=UTF-8',
   location: 'http://www.google.com.au/?gfe_rd=cr&ei=Mpx2VfmnF6nu8wfUioDQBQ',
  'content-length': '262',
   date: 'Tue, 09 Jun 2015 07:56:34 GMT',
 server: 'GFE/2.0',
'alternate-protocol': '80:quic,p=0',
connection: 'close' }
<HTML><HEAD><meta http-equiv="content-type" content="text/html;charset=utf-8">
<TITLE>302 Moved</TITLE></HEAD><BODY>
<H1>302 Moved</H1>
The document has moved
<A HREF="http://www.google.com.au/?    gfe_rd=cr&amp;ei=Mpx2VfmnF6nu8wfUioDQBQ">here</A>.
</BODY></HTML>
This doesn't get logged out