Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Node http.request does nothing

var http = require('http');

var options = {
    method: 'GET',
    host: 'www.google.com',
    port: 80,
    path: '/index.html'
};

http.request(
    options,
    function(err, resBody){
        console.log("hey");
        console.log(resBody);
        if (err) {
            console.log("YOYO");
            return;
        }
    }
);

For some reason this just times out and doesn't log anything to the console.

I'm aware that I could require('request') but I need to use http to be compatible with a plugin I'm using.

Also, background on my versions: Node is v0.8.2

like image 360
bgcode Avatar asked Feb 12 '13 22:02

bgcode


2 Answers

Use the example here: http://nodejs.org/api/http.html#http_http_request_options_callback

var options = {
  hostname: 'www.google.com',
  port: 80,
  path: '/upload',
  method: 'POST'
};

var req = http.request(options, function(res) {
  console.log('STATUS: ' + res.statusCode);
  console.log('HEADERS: ' + JSON.stringify(res.headers));
  res.setEncoding('utf8');
  res.on('data', function (chunk) {
    console.log('BODY: ' + chunk);
  });
});

req.on('error', function(e) {
  console.log('problem with request: ' + e.message);
});

// write data to request body
req.write('data\n');
req.write('data\n');
req.end();

the callback does not have an error parameter, you should use on("error", ...) and your request doesn't get sent till you call end()

like image 110
Pascal Belloncle Avatar answered Oct 21 '22 19:10

Pascal Belloncle


You prepared a request object, but didn't fire it with .end(). (Also the callback doesn't work that way.)

See: http://nodejs.org/api/http.html#http_event_request

like image 38
cjb Avatar answered Oct 21 '22 19:10

cjb