Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making request to localhost with Node client?

Tags:

node.js

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);
});
like image 425
r123454321 Avatar asked Sep 03 '15 16:09

r123454321


People also ask

How do I connect to a client and server in node JS?

connect(PORT, HOST, () => { console. log(`client connected to ${HOST}:${PORT}`); // Write a message to the socket as soon as the client is connected, the server will receive it as message from the client client.

How do I use HTTP request in node?

Step to run the application: Open the terminal and write the following command. Approach 3 : Here we will send a request to updating a resource using node-fetch library. If you are already worked with Fetch in browser then it may be your good choice for your NodeJS server. Rewrite the index.

How do I send HTTP POST request in node?

Example code: var request = require('request') var options = { method: 'post', body: postData, // Javascript object json: true, // Use,If you are sending JSON data url: url, headers: { // Specify headers, If any } } request(options, function (err, res, body) { if (err) { console. log('Error :', err) return } console.


1 Answers

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');
like image 87
Matt Harrison Avatar answered Oct 20 '22 21:10

Matt Harrison