当事件来自 Django 服务器时,不调用 EventSource addEventListener 回调方法

EventSource addEventListener callback method is not called when event comes from Django server

EventSource addEventListener 回调在事件到来时不被调用

设置: 姜戈 2.0.7 Chrome67.0.3396.99 MacOSX 10.13.6 (17G65)

源代码: 在我的 chat.html:

<script src="{% static 'django_eventstream/json2.js' %}" charset="utf-8"></script>
    <script src="{% static 'django_eventstream/eventsource.min.js' %}" charset="utf-8"></script>
    <script src="{% static 'chat/jquery-3.2.1.min.js' %}" charset="utf-8}"></script>

    <script type="text/javascript">

      var testPubSub = function(user) {
        var uri = 'events/?channel=room-' + encodeURIComponent('{{ room_id }}');
        var es = new EventSource(uri, {
          lastEventId: '{{ last_id }}'
        });

        var firstConnect = true;

        es.onopen = function() {
          if (!firstConnect) {
            console.log('*** Connected');
          }
          firstConnect = false;
        }

        es.onerror = function() {
          console.log('*** connection lost');
        };

        console.log('before addEventListener');

        es.addEventListener('message', function(e) {
          console.log('addEventListener event');
          console.log('event: ' + e.data);
          msg = JSON.parse(e.data);

          console.log();
        }, false);
        console.log('after addEventListener');

        $('#send-form').submit(function() {
          var text = $('#chat-input').val();
          $.post('/rooms/{{ room_id }}/messages/', {from: user, text: text}
          ).done(function(data) {
            console.log('send response:' + JSON.stringify(data));
          }).fail(function() {
            alert('failed to send message');
          }).always(function() {
            $('#chat-input').val('');
            $('#chat-input').focus();
          });

          return false;
        });

        $('#chat-input').focus();
      };

      $(function() {
        testPubSub('{{ user|escapejs }}');
      });
    </script>
  </head>

  <body>
    <div id="chat-input-area">
      <form id="send-form">
        <button id="send-button">Send</button>
        <span id="chat-input-span"><input type="text" id="chat-input" autocomplete="off" /></span>
      </form>
    </div>
  </body>

从控制台日志中,我可以看到当我按下发送按钮时,打印了以下日志:
before addEventListener after addEventListener send response:"333"

但是 addEventListener event 没有打印在日志中。

从 HTTP 数据包中,我可以看到 Django 服务器发送了带有 'event: ' 的 HTTP 数据包:

POST /publish/ HTTP/1.1 Host: localhost:5561 User-Agent: python-requests/2.19.1 Accept-Encoding: gzip, deflate Accept: */* Connection: keep-alive Content-Type: application/json Content-Length: 130 JS Objection Notation: {"items": [{"http-stream": {"content-filters": [], "content": "event: message\ndata: \"333\"\n\n"}, "channel": "events-room-r1"}]}

我自己想通了原因。

addEventListener 可以。我在 Django 中的路由配置有问题(奇怪的是,Django 根本没有抱怨)。

我使用了大量的日志打印来查明根本原因,在我在 Django 中重新配置路由后,问题就解决了。