user2411290
user2411290

Reputation: 641

Basic chat application with socket/node/express - Nothing gets printed out

I am just trying to do a very basic chat application with socket.io and node. I am unable to see anything get printed out to my screen, and cannot find any errors. Appreciate the help!

Thanks.

app.js

var express = require('express');
var app = express();
var server = require('http').createServer(app);
var io = require('socket.io').listen(server);

server.listen(3000);
console.log('Server running...');

app.get('/', function(req, res){

    res.sendFile(__dirname + '/index.html');

});

io.sockets.on('connection', function(socket){
    socket.on('send-message', function(data){
        io.sockets.emit('new message', data);
    });
});

index.html

<html>
<title>Chat Test</title>

<style> #chat{
height: 500px;
}
</style>
<head>
<body>

<div id = "chat"></div>

<form id = "send-message">
    <input size = "35" id = "message"></input>
    <input type = "submit"></input>
    </form>

    <script src ="https://code.jquery.com/jquery-latest.min.js"></script>
    <script src ="/socket.io/socket.io.js"></script>

    <script>

    JQuery(function($){

        var socket = io.connect();

        var $messageForm = $('#send-message');
        var $messageBox = $('#message');
        var $chat = $('#chat');

        $messageForm.submit(function(e){

        e.preventDefault();
        socket.emit('send-message', $messageBox.val());
        $messageBox.val('');

        });

        socket.on('new message', function(data){
        $chat.append(data + "<br/>");
        });
    });

    </script>
</body>
</head>
</html>

Upvotes: 0

Views: 112

Answers (1)

jfriend00
jfriend00

Reputation: 707328

When using jQuery, you must spell it jQuery, not JQuery or you could just use the built-in alias $.

This should have shown an error in the debug console of the browser which is something you should learn to look for to see your own errors.

jQuery(function($){

    var socket = io.connect();

    var $messageForm = $('#send-message');
    var $messageBox = $('#message');
    var $chat = $('#chat');

    $messageForm.submit(function(e){

        e.preventDefault();
        socket.emit('send-message', $messageBox.val());
        $messageBox.val('');

    });

    socket.on('new message', function(data){
        $chat.append(data + "<br/>");
    });
});

After fixing this and then running your code and accessing http://localhost:3000, your app works just fine for me. Anything submitted in the form is broadcast to all connected clients.

Upvotes: 2

Related Questions