Orion
Orion

Reputation: 174

error trying to set up basic chat app with node.js

I am trying to set up a basic chat app with node.js/express/socket.io but for some reason when the client sends message (this works, another client will get the message) it also refreshes the client and the url goes from localhost:3000 to localhost:3000/? (adds /? to end, i don't know what this means). I cant find anything wrong in my code after looking at it for hours. I have:

server.js:

let app = require('express')();
let http = require('http').Server(app);
let io = require('socket.io')(http);
let port = process.env.PORT || 3000;

app.get('/', (req, res) => { res.sendFile(__dirname + '/index.html') });

http.listen(port,() => { console.log('listening on *:' + port) });

    io.on('connection', socket => {
        socket.on('chat', text => {
        io.sockets.emit('chat', `<p>${text}</p>`);
    });

});

index.html:

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<script src="/socket.io/socket.io.js"></script>
<script src="https://code.jquery.com/jquery-1.11.1.js"></script>
<style>
    .chat_view{
        height: 300px;
        width: 200px;
        border: 5px ridge black;
        overflow-y: scroll;
    }
</style>
</head>
<body>
<div class="chat" id="chat">
    <div class="chat_view" id="chat_view">
    </div>
    <form id="chat_form">
        <input type="text" title="chat_input" id="chat_input" style="width: 206px">
    </form>
</div>
<script>
let socket = io();

$('#chat_form').submit( () => {
    let text = $('#chat_input').val();
    socket.emit('chat', text);
});

socket.on('chat', text => {
    let chat_view = document.getElementById('chat_view');
        chat_view.innerHTML += text;
        chat_view.scrollTop = chat_view.scrollHeight;
});

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

and package.json:

{
  "name": "RatScrew",
  "version": "0.0.1",
  "dependencies": {
    "express": "^4.15.3",
    "socket.io": "^2.0.2"
  }
}

Upvotes: 0

Views: 69

Answers (2)

mk12ok
mk12ok

Reputation: 1313

Change your code to:

$('#chat_form').submit((event)=>{
    event.preventDefault();
    let text = $('#chat_input').val();
    socket.emit('chat', text);
});

The default method used when submiting the form is the GET method, which makes the server send index.html again and the page refreshes.
You may want to have a look at https://www.w3.org/TR/html401/interact/forms.html

Upvotes: 1

Paul
Paul

Reputation: 36349

If you're listening to the submit event, that means the form will actually try and POST to the server (which will in your case refresh the screen). If you're using JavaScript to communicate with the server and don't need the form data to get posted by the browser directly, just return false from your callback. Some browsers also want you to call e.preventDefault() as well.

Upvotes: 3

Related Questions