index.js
const messageContainer = document.querySelector('.msg');
const append = (message, position) => {
console.log(message)
const messageElement = document.createElement('div');
messageElement.innerText = message;
messageElement.classList.add('message');
messageElement.classList.add(position);
console.log(messageElement)
messageContainer.append(messageElement);
console.log(messageContainer)
};
const SERVER = "http://localhost:3010";
var socket = io(SERVER);
socket.on('receive_message', (message) => {
console.log('Connected');
console.log(message.content);
setRMsg(message);
console.log(rmsg)
// append(`${message ? message.name : ''}: ${message ? message.content : ''}`, 'right');
// // if (message.sendBy === 'user') {
// append(`${message.content} `, 'left');
// };
});
console.log(rmsg);
if (rmsg && rmsg != '') {
append(`${rmsg.content} `, 'left');
setRMsg('')
}
const send = () => {
console.log('*95')
console.log(sending)
if (sending === '' || sending.senderChatID === '' || sending.content === '' || id === '') {
console.log('***')
toast.error('Missing Required Field', {
position: "top-right",
hideProgressBar: false,
closeOnClick: true,
pauseOnHover: true,
});
}
else {
let obj = {
senderChatID: sending.senderChatID,
receiverChatID: id,
content: sending.content,
sendBy: sendVia,
chatId: id,
name: name ? name.name : '',
profile_pic: name ? name.profile_pic : '',
role: name ? name.role : '',
createdAt: new Date(Date.now()),
user_id: id
};
append(`${name ? name.name : ''}: ${sending.content}`, 'right');
const input = document.getElementById('messageInp');
input.value = '';
socket.emit('send_message', obj);
}
'recieve_message' 事件被多次点击,但它必须点击一次,而点击按钮发送功能工作正常,但在接收消息时它被多次点击不知道为什么,因为我是 socket.io 的新手,可能是我在做小错误。任何帮助将不胜感激