NodeJs Error: connect ETIMEDOUT

2019-05-11 01:35发布

问题:

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)

回答1:

I see at least two things wrong here:

  1. 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.

  2. 'Content-Length': 'post_data.length' should be 'Content-Length': post_data.length



回答2:

You have to call subscribeRequest.end() after declaring your request! If you don't do it, your request will never be sent



标签: node.js http