r123454321
r123454321

Reputation: 3403

Making request to localhost with Node client?

I have a very simple node server running on port 8080, and I'm trying to get an equally simple node client to hit this server.

Why does this code not work:

var http = require('https');

http.get('http://localhost:8080/headers', function(response) {
    console.log('Status:', response.statusCode);
    console.log('Headers: ', response.headers);
    response.pipe(process.stdout);
});

but this code does work?:

var http = require('http');
var client = http.createClient(8080, 'localhost');
var request = client.request('GET', '/headers');
request.end();
request.on("response", function (response) {
    console.log('Status:', response.statusCode);
    console.log('Headers: ', response.headers);
    response.pipe(process.stdout);
});

Upvotes: 11

Views: 20144

Answers (1)

Matt Harrison
Matt Harrison

Reputation: 13557

Because you're loading the https module but trying to make a plain old HTTP request. You should use http instead.

var http = require('https');

should be:

var http = require('http');

Upvotes: 19

Related Questions