从 Flask 套接字检索消息会引发"Invalid left-hand side in assignment"



我正在尝试创建一个可以使用Flask套接字和Javascript加入的通道。

我所有的调试语句都在触发,表明一切都在初始化,但是当我尝试捕获从我的 Flask/socket-io 路由发出的消息时,我假设它执行实际的房间更改,我在控制台中得到Uncaught ReferenceError: Invalid left-hand side in assignment引用我的 JS 文件中的行let message = data.msg;在本节中:

socket.on('status', data => {
let message = data.msg;
document.querySelectorAll('#messages') += message;
});

我尝试以各种方式编写data.msg(例如,使用反引号,例如 ${data.msg} 被反引号包围,就好像格式化字符串的一部分一样(,但没有任何效果。我读过文档,它们的细节很少。似乎没有关于如何在网络上有效地做到这一点的例子。大多数人似乎都喜欢node.js,但我是一个Flask的人。

如何加入我的房间,并只在那个房间里聊天?我需要允许用户创建任意数量的用户。

这是Flask中的路线:

@socketio.on('join')
def on_join(data):
username = data['username']
room = data['room']
join_room(room)
emit("status", {'msg': username + 'has joined the room'}, room=room)

以下是随附的JS:

var socket = io.connect(location.protocol + '//' + document.domain + ':' + location.port);
if (!socket) console.log("Socket not connected!");
socket.on('connect', () => {
console.log("socket connected");
// after socket connect, configure channel button
document.querySelectorAll('button').forEach(button => {
button.onclick = () => {
console.log("button click fired!");
let username = localStorage["login"]
let room = button.dataset.room;
console.log("ChannelName" + room);
socket.emit("join", {'username':username, "room":room});
};
});
socket.on('status', data => {
console.log("JOINED!")
let message = data.msg;
document.querySelectorAll('#messages') += message;
});

请注意,错误发生在分配给#messagediv之前

编辑解压缩错误会显示对缩小的 JS 文件烧瓶套接字 io-io 要求的多个引用。它在layout.html<head>部分。放置在<body>中会导致严重错误,阻碍了所有套接字相关功能的开发。

messages:134 Uncaught ReferenceError: Invalid left-hand side in assignment
at r.socket.on.data (messages:134)
at r.n.emit (socket.io.min.js:1)
at r.onevent (socket.io.min.js:1)
at r.onpacket (socket.io.min.js:1)
at n.<anonymous> (socket.io.min.js:1)
at n.emit (socket.io.min.js:1)
at n.ondecoded (socket.io.min.js:1)
at s.<anonymous> (socket.io.min.js:1)
at s.n.emit (socket.io.min.js:1)
at s.add (socket.io.min.js:2)

这是无效的:document.querySelectorAll('#messages') += message;

document.querySelectorAll('#messages')会给你一个 DOM 元素的列表。

此外,元素 id 应该是唯一的,因此您可能应该使用document.querySelector('#messages')因此只检索一个元素,而不是列表。

您不能以这种方式直接向元素添加/连接文本。您可能正在寻找类似document.querySelector('#messages').innerHTML += message;

相关内容

最新更新