Dhruv Chadha Dhruv Chadha - 2 months ago 9
Node.js Question

Chat server using socket.io, message not appending to list

I was trying to implement a chat server in node.js using socket.io, as given on the socket.io website. Everything seems to work fine except that the messages are not getting appended in the list I have made on the client side's HTML code.
Can someone tell me what I'm doing wrong?

server code

var express = require('express');
var soc = require('socket.io')
var http = require('http');
var ip = require('ip');

var app = express();
var server = http.createServer(app).listen(3000);
var io = soc(server);

app.get('/', function(req, res) {
res.sendFile(__dirname + "/chat.html");
});

io.on('connection', function(socket) {
var address = socket.handshake.address;
var pos = address.indexOf('1');
var len = address.length;
address = address.slice(-1 * (len - pos));
/*if(address[0] === ':') {
address = ip.address();
}*/
console.log(address + ' connected');
socket.on('disconnect', function() {
console.log(address + ' disconnected');
});
socket.on('message', function(message) {
io.emit('update', message);
});
});


client code

<html>
<head></head>
<body>
<form id="form" action="" style="position: absolute; bottom: 0; width: 100%;">
Chat: <input style="width: 90%;" type="text" name="chat">
<input type="submit" style="margin: 2px 50%">
</form>
<ul id="myList"></ul>
<script src="/socket.io/socket.io.js"></script>
<script>
var myList = document.getElementById('myList');
var socket = io();
var form = document.getElementById("form");
form.addEventListener("submit", function() {
socket.emit('message', form.chat.value);
});
socket.on('update', function(msg) {
var node = document.createElement('li');
var textnode = document.createTextNode(msg);
node.appendChild(textnode);
document.getElementById('myList').appendChild(node);
});
</script>
</body>



Answer

It does add it to the list, but then gets cleared immediately when the page reloads as a result of you submitting a form.

Try calling preventDefault() on the event thats passed into the submit handler in chat.html:

form.addEventListener("submit", function(event) {
    event.preventDefault();
    socket.emit('message', form.chat.value);
});