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"
}
}
via Orion
No comments:
Post a Comment