0

I am new to node, so please bear with me. I'm trying to write a function that tests to make sure there is a live connection to the web server before redirecting the page.

This works for the first 6 - 7 clicks, then the page will not redirect anymore - it just sits there. Then a few minutes later, an alert will show.

What is going on?!

var http = require("http");
var url = 'http://example.com/';

mainMenu.click(function () {
  var menulink = $(this).attr('rel');
  var menuvar = http.get(url, function () {
    window.location = menulink;
  }).on('error', function () {
    alert('Cannot Connect to Server');
  });
});
hexacyanide
  • 88,222
  • 31
  • 159
  • 162

1 Answers1

0

I suspect you have a problem with non-flowing streams.

Since you never consume the data of your responses, the connection never closes. The HTTP Agent limits the number of concurrent connections and refuses to open any new connection after a while.

You should try to manually switch the response to flowing mode:

mainMenu.click(function () {
  var menulink = $(this).attr('rel');
  var menuvar = http.get(url, function (res) {
    // FORCE FLOWING MODE
    res.resume();
    window.location = menulink;
  }).on('error', function () {
    alert('Cannot Connect to Server');
  });
});
Laurent Perrin
  • 14,671
  • 5
  • 50
  • 49
  • Thanks! That took care of it. Is this the best method to deal with this? Is there a way to close the connection? –  Sep 27 '13 at 18:19
  • That's the best method: it will consume all the data and let the server will close the response. – Laurent Perrin Sep 27 '13 at 18:36