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);
});
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.
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.
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.
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');
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With