【问题标题】:Socket.io does not emit anything when a message is sent发送消息时,Socket.io 不发出任何内容
【发布时间】:2020-07-01 21:59:26
【问题描述】:

预期的结果是,在用户按下“回车”键或发送按钮后,消息应显示在聊天框中。但是,这两个事件没有任何反应,并且没有聊天记录保存在数据库中。

在 chrome 控制台中,我收到以下错误:

chat.js:7 Uncaught TypeError: Cannot read property 'addEventListener' of null
    at n.<anonymous> (chat.js:7)
    at n.emit (socket.io.slim.js:6)
    at n.emit (socket.io.slim.js:8)
    at n.onconnect (socket.io.slim.js:8)
    at n.onpacket (socket.io.slim.js:8)
    at n.<anonymous> (socket.io.slim.js:8)
    at n.emit (socket.io.slim.js:6)
    at n.ondecoded (socket.io.slim.js:6)
    at a.<anonymous> (socket.io.slim.js:8)
    at a.n.emit (socket.io.slim.js:6)

其他一切都应该正常工作,因为当我手动将聊天添加到数据库时,它们会出现在聊天框中。

这里是 javascript 文件:

document.addEventListener('DOMContentLoaded', () => {
    var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);

    socket.on('connect', () => {

        // allow "Enter" key to send message
        document.querySelector('#text').addEventListener("keydown", event => {
            if (event.key == "Enter") {
                document.getElementById('#button-send').click();
            }
        })

        document.querySelector("#button-send").addEventListener("click", () => {

            let timestamp = new Date;
            timestamp = timestamp.toLocaleTimeString();

            // Save user input
            let msg = document.getElementById("text").value;

            socket.emit('send message', msg, timestamp)

            document.getElementById("text").value = '';
        });
    });

    socket.on('announce message', data => {

        // Format message
        if (data.friend_id === data.user_id) {
            let row1 = data.msg
            let row2 = data.timestamp
            document.querySelector('#newmsg').value += row 
            document.querySelector('#newdate').value += row 
        }
        else {
            let row1 = data.msg
            let row2 = data.timestamp
            document.querySelector('#newchat').value += row 
            document.querySelector('#newchat').value += row 
        }      
    })
})

这里是 app.py:

@socketio.on("send message")
def send_msg(msg, timestamp):
    chat = session.get['friend']

    friend_id = db.execute("SELECT id FROM users WHERE username=:username", {"username":chat}).fetchone()[0]

    convo_id = db.execute("SELECT chat_id FROM chat_ids WHERE p1_id =: p1_id, p2_id =: p2_id", {"p1_id":session["user_id"], "p2_id":friend_id})

    db.execute("INSERT INTO messages (conversation_id, sender, reciever, time, message) VALUES (:id, :sender, :reciever, :time, :message)", 
        {"coversation_id": convo_id, "sender":session["user_id"], "reciever": friend_id, "time":timestamp, "message":msg})

    emit('announce message', {
        'timestamp': timestamp,
        'msg': msg,
        'user_id':session["user_id"],
        'friend_id': friend_id},
        chat = chat)

这里是相关的html文件

<body>
        <div class="messaging">
          <div class="inbox_msg">
              <div class="mesgs">
                <div class="msg_history">
                  {% for message in messages %}
                    {% if message["sender"] == session.user_id %}
                      <div class="outgoing_msg">
                        <div class="sent_msg">
                          <p id="newmsg">{{message[3]}}</p>
                          <span class="time_date" id="newdate">{{message[2]}}</span>
                        </div>
                    {% else %}
                        <div class="incoming_msg">
                          <div class="incoming_msg_img"><img src="https://ptetutorials.com/images/user-profile.png" alt="">
                            <div class="received_withd_msg">
                              <p id="newmsg">{{message[3]}}</p>
                              <span class="time_date" id="newdate">{{message[2]}}</span>
                            </div>
                          </div>
                        </div>
                      </div>
                    {% endif %}
                  {% endfor %}
                </div>
                <div class="type_msg">
                  <div class="input_msg_write">
                    <input id="msg" type="text" class="write_msg" placeholder="Type a message" />
                    <button id="button-send" class="msg_send_btn" type="button"><i class="fa fa-paper-plane-o" aria-hidden="true"></i></button>
                  </div>
                </div>
              </div>
          </div>
        </div>
   </div>
</body>

【问题讨论】:

  • Uncaught TypeError: Cannot read property 'addEventListener' of null 表示您正在尝试将事件侦听器附加到其中没有任何内容的对象变量。
  • 因此您的查询选择器之一可能失败了。检查以确保每个查询选择器实际上都返回了您在查询字符串中指定的对象。

标签: javascript python flask socket.io


【解决方案1】:

错误

chat.js:7 Uncaught TypeError: Cannot read property 'addEventListener' of null

如其所述;事件被附加到 null 类型的对象。它发生在以下行

document.querySelector('#text').addEventListener("keydown", event => {

确保名为textid 是有效的,您还应该考虑使id 名称更加独特。此外,如果您的Js 文件位于HTML 文件的head 部分中,并且您使用#text 进行的引用在body 部分中定义,也会发生这种情况。请参阅here 以获得更好的解释。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-24
    • 1970-01-01
    • 2022-10-31
    • 2019-06-11
    • 2017-03-05
    相关资源
    最近更新 更多