I am making a basic chat app in Replit Node.JS and I do not know what I did but now, chat messages are not going through. The server can still detect when the users have connected and disconnected, but new chat messages don’t get through, and I only see the ones I send.
Here is the link to the project. (PLEASE NOTE THAT THE PROBLEM PROBABLY HAS TO DO WITH THE INDEX.HTML FILE, WHICH IS LOCATED IN THE PUBLIC FOLDER. IT HAS BEEN THE ONLY THING I HAVE BEEN EDITING)
https://replit.com/@OSoft/OChat-ALPHA?v=1
Line 202, you probably also want to check if the username was stored in localStorage
. Something like this:
const username = usernameInput.value.trim() || window.localStorage.getItem("username", null) || "Unknown User";
window.localStorage.setItem("username", username);
Then you don’t need the if
statement on line 204. That should fix issues where no username is entered.
I think the main issue is just that you’ve named the event you’re listening for on the client side differently to what you’ve named it server side. On the client you’re emitting and listening for a chat message
event, whereas on the server, you’re emitting and listening for a message
event
So what exactly should I do? (Again, I can sometimes make things feel very vague for myself. I apologize)
In the HTML file, change "chat message"
to "message"
where you call emit
and where you call on
.
Thank you. A quick question: Why is it when I leave the chat (close the window), it prints “undefined:undefined”?
On line 33 in server.js
; you send a string, but on the client-side, you are expecting an object with a username
and message
property. So a simple fix would be to send this for example instead: { username: "system", message: "A user has left the chat." }
I’m not sure I follow.
In the server.js
file, when a socket
disconnects, line 33, instead of emitting this: "A user has left the chat"
, emit this: { username: "system", message: "A user has left the chat." }
Ah okay. It worked. Thank you for your time.
I saw you say “Hello World” through the program.
Yep, it’s definitely working then! Did you see the disconnect message?
Yes, I did! Thanks for helping with that!
This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.