NodeJs Error: connect ETIMEDOUT

2019-05-11 01:31发布

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)

标签: node.js http
2条回答
forever°为你锁心
2楼-- · 2019-05-11 01:58

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

查看更多
神经病院院长
3楼-- · 2019-05-11 02:10

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

查看更多
登录 后发表回答