[英]How to make typed chat messages display on the screen? (socket.io and node.js)
I'm working on creating a chat app using socket.io and node.js, the server is connected, and both socket.io and client-side socket.io are connected, yet when I type something on the localhost page and press enter, it doesn't show anything on这页纸。 如何让我的聊天出现在页面上? 先感谢您。
<index.js>
const express = require('express');
const app = express();
const http = require('http');
const port = process.env.PORT || 3000;
const server = http.createServer(app);
const { Server } = require('socket.io');
const io = new Server(server);
app.use(express.static(__dirname + '/public'));
app.get('/', (req, res) => {
res.sendFile(__dirname + '/index.html');
});
io.on('connection', (socket) => {
socket.on('chat message', (msg) => {
io.emit('message:' + msg);
});
});
server.listen(port, () => {
console.log(`Server is running on port: ${port}`);
});
<script.js>
var socket = io();
var messages = document.getElementById('messages');
var form = document.getElementById('form');
var input = document.getElementById('input');
form.addEventListener('submit', function(e) {
e.preventDefault();
if (input.value) {
socket.emit('chat message', input.value);
input.value = '';
}
});
socket.on('chat message', function(msg) {
var item = document.createElement('li');
item.textContent = msg;
messages.appendChild(item);
window.scrollTo(0, document.body.scrollHeight);
});
<index.html>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="./style.css">
<title>Chat App</title>
</head>
<body>
<ul id="messages"></ul>
<form id="form" action="">
<input id="input" autocomplete="off">
<button>Send</button>
</form>
<script src="/socket.io/socket.io.js"></script>
<script src="./script.js"></script>
</body>
</html>
在你的 index.html 试试这个
<button type="submit">Send</button>
因为你的听众监听提交事件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.