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, it just shuts off and writes nothing to the console.

I know I can require('request') , but I need to use http for compatibility with the plugin I use.

Also, background in my versions: Node v0.8.2

+4
source share
3 answers

Use an 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 must use it ("error", ...) and your request is not sent until you call end ()

+3
source

You prepared the request object, but did not miss it with .end (). (Also the callback does not work this way.)

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

+3
source

The pair is here:

  • Use hostname not host so you are compatible with url.parse() ( see here )
  • The callback for the request takes one argument, which is http.ClientResponse
  • To catch the error, use req.on('error', ...)
  • When using http.request you need to complete the request when you finish req.end() so that you can write any body you need (using req.write() ) before the request ends
    • Note: http.get() will do this for you under the hood, and so you forgot.

Work code:

 var http = require('http'); var options = { method: 'GET', hostname: 'www.google.com', port: 80, path: '/index.html' }; var req = http.request( options, function(res){ console.log("hey"); console.log(res); } ); req.on('error', function(err) { console.log('problem', err); }); req.end(); 
0
source

All Articles