NodeJS HTTP request connection's close event fired twice

随声附和 提交于 2020-01-05 07:53:46

问题


I'm working on realtime AJAX application with long polling in NodeJS. I would like to detect when user closes the tab with pending long-polling request. I use NodeJS connection close event:

request.connection.on('close', function () {
  console.log(request.url);      
  ... 
}); 

The AJAX loop looks like this:

var EventLoop = new (function () {

  var self = this;

  this.listen = function () {
    $.postJSON(
      'recieve-events', 
      { /* some data not important for this issue */ }, 
      function (data) {
        ...
        self.listen();
      }
    );
  }

})();     

This is how the postJSON function is defined:

$.extend({
  postJSON: function (url, data, callback) {
    $.ajax({
      'url': url, 
      'dataType': 'json', 
      'data': data,
      'type': 'POST', 
      'success': callback
    });
  }
});

The problem is, that the connection close event is fired twice, when I close the tab. Can anyone explain me why and how to prevent this behaviour?

I know, that I can use counter and call the callback function just first time, but I don't consider this as a nice solution, since it doesn't make logical sense to me to close something, that is already closed. (firing the event twice)

来源:https://stackoverflow.com/questions/7221937/nodejs-http-request-connections-close-event-fired-twice

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!