简体   繁体   中英

Socket.io does not emit anything when a message is sent

The expected result is that after the user presses "enter" key or the send button that the message should display in the chat box. However, nothing occurs upon these two events and no chat is saved in the database.

In the chrome console, I am getting the following errors:

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)

Everything else should be working fine, as when I manually add chats to the database, they appear in the chatbox.

Here is the javascript file:

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 
        }      
    })
})

Here is the 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)

Here is the relevant html file

<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>

The error

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

as it states; the event is being attached to an object that is of type null. It occurs on the following line

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

Make sure that the id called text is valid and you should also consider making id name bit more unique. Moreover, this can also happen if your Js file is in the head section of your HTML file and the reference you make with #text is defined in the body section. See here for a better explanation.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM