I run node myserver.js
that contains the code bellow, and after 40-50sec I get the error(bellow the code). Why do I get an error when nothing is happening?
var options = {
host: 'google.com',
port: '80',
path: '/',
method: 'POST',
headers: {
'Content-Type': 'application/x-www-form-urlencoded',
'Content-Length': 'post_data.length'
}
};
var subscribeRequest = require('http').request(options, function(res) {
console.log('send request');
}).on('error', function(err){console.log(err.stack)});
after 40-50sec I get this error:
Error: connect ETIMEDOUT
at errnoException (net.js:904:11)
at Object.afterConnect [as oncomplete] (net.js:895:19)
You have to call
subscribeRequest.end()
after declaring your request! If you don't do it, your request will never be sentI see at least two things wrong here:
You're not ending your request. When you use
http.request()
you have to call.end()
on the request object returned when you are done sending any data so that the server knows there is no more data coming.http.get()
automatically calls.end()
for you because there are no bodies with GET requests.'Content-Length': 'post_data.length'
should be'Content-Length': post_data.length