Nodejs http request not working

Viewed 18306

I have a piece of code that's supposed to do a http get request. The program exited successfully without error, but I didn't see any response and it didn't even go inside the callback function! At first I thought it's because http is asynchronous and put a large loop in the end but that didn't work either. Does anyone know this issue? Only the first console log sendHttpRequest and 444 gets printed. I also tried the http.get but it didn't work either.

function sendHttpRequest (url, callBack) {
    console.log("sendHttpRequest");
    //constrct options
    var options = {
        host: 'www.google.com',
        path: '/index.html',
        method: 'GET',
        headers: {
           'Content-Type': 'application/x-www-form-urlencoded'
        }
    };

    http.get("http://www.google.com/index.html", function(res) {
        console.log("Got response: " + res.statusCode);
    });

    var req = http.request(options, function(res) {
        console.log("333");
        var output = '';
        console.log(options.host + ':' + res.statusCode);
        res.setEncoding('utf8');

        res.on('data', function (chunk) {
            console.log("DATATATAT!")
            output += chunk;
        });

        res.on('end', function () {
            console.log('222');
            var obj = JSON.parse(output);
            callBack(res.statusCode, obj);
        });
    });

    req.on('error', function (err) {
        console.log('error: ' + err.message);
    });

    req.end();
    console.log("444");
    }
}
1 Answers
Related