Search code examples
javascriptnode.jshttphttp-request

NodeJS 'http' object is supposed to have a method called get() but where is it?


I would like to see in my console either "Got response" or "Got error".

I've been trying to perform an HTTP request using http.get() but I get the following error when I try.

D:\wamp\www\Chat\server\test.js:19
http.get("http://google.com", function(res) {
     ^
TypeError: Object #<Server> has no method 'get'
    at Object.<anonymous> (D:\wamp\www\Chat\server\test.js:19:6)
    at Module._compile (module.js:449:26)
    at Object.Module._extensions..js (module.js:467:10)
    at Module.load (module.js:356:32)
    at Function.Module._load (module.js:312:12)
    at Module.runMain (module.js:492:10)
    at process.startup.processNextTick.process._tickCallback (node.js:244:9)

Here is test.js in its entirety:

var http = require('http').createServer(handler);

var fs = require('fs');

http.listen(9090);

function handler(req, res) {
    fs.readFile(__dirname + '/index.html', function(err, data) {
        if (err) {
            res.writeHead(500);
            return res.end('Error loading index.html');
        }

        res.writeHead(200);
        res.end(data);
    });
}

http.get("http://google.com", function(res) {
    console.log("Got response: " + res.statusCode);
}).on('error', function(e) {
    console.log("Got error: " + e.message);
});

Executing node --version in cmd returns v0.8.15


Solution

  • you're calling get() on the server you created, not on the http object:

    var http = require('http').createServer(handler);
    

    your http should be:

    var http = require('http');
    

    then you can use http.get();