Question

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

Was it helpful?

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();

OTHER TIPS

The http module does in fact have a top-level get method, but your variable http is a reference to an instance of http.Server rather than to the module itself. Servers don't have methods for making client requests. Change the first few lines to

var http = require('http');

var fs = require('fs');

http.createServer(handler).listen(9090);

Your problem is that you are asking an httpServer to do get, and not http itself! The get method will work if you do it like this:

var http = require('http');

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

This does not require creating a server.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top