Assaf
Assaf

Reputation: 808

node.js cannot make rest call with http

I am new to node.js and I am trying to make an http request. I followed a tutorial trying to call random.org. this is my app.js file:

var http = require('http');

//The url we want is: 'www.random.org/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
var options = {
  host: 'www.random.org',
  path: '/integers/?num=1&min=1&max=10&col=1&base=10&format=plain&rnd=new'
};

callback = function(response) {
  var str = '';

  //another chunk of data has been recieved, so append it to `str`
  response.on('data', function (chunk) {
    str += chunk;
  });

  //the whole response has been recieved, so we just print it out here
  response.on('end', function () {
    console.log(str);
  });

  response.on('error', function () {
    console.log("err");
  });
}

http.request(options, callback).end();

So, anyway, when running this file using

node app.js

I get the following error to the console:

C:\Program Files\nodejs>node app.js

events.js:72
        throw er; // Unhandled 'error' event
              ^
Error: connect ETIMEDOUT
    at errnoException (net.js:901:11)
    at Object.afterConnect [as oncomplete] (net.js:892:19)

2 problems:
1. Why am I getting time out error (the site works - I checked)
2. Anyway - why am I not catching this error althought I have an error listener in the response.

Any possible help will be much appreciated!

Thanks

Upvotes: 1

Views: 2783

Answers (2)

Assaf
Assaf

Reputation: 808

OK. I tried to run this as standalone node js process without browser as background. This is not recommended, and in the cases specified above the problem was that this headerless request lacked cookies.

If I would wrap everything in a createServer method, and upon request I would do the http.request with the same parameters + the cookies from the server request - this would work.

Upvotes: 0

user568109
user568109

Reputation: 47993

You are attaching the error listener to the response, but error happens in request itself. Do someting like this :

http.request(options, callback)
.on('error', function () {
    console.log("err in request");
})
.end();

The error means the site is available, if not the error would show EHOSTUNREACH. ETIMEDOUT means that request was not responded fast enough. It needs some investigation, lke is the network down, try getting www.google.com. What is the timeout value it is considering ? etc.

Upvotes: 4

Related Questions