NodeJS聊天消息无法打印至控制台问题排查请求
Socket.io 聊天消息终端无输出问题调试
问题根源及修复点
- 客户端发送DOM元素而非输入值:直接传递
input元素对象给服务端,需改为获取元素的.value属性拿到用户输入内容。 - 服务端使用未定义的
join函数:JavaScript无全局join函数,改用字符串拼接或数组join方法。 - 客户端socket.io.js路径错误:绝对路径易引发环境适配问题,改用服务端自动提供的相对路径
/socket.io/socket.io.js。
修正后的服务端代码
const http = require("http"); const host = 'localhost'; const port = 8000; const express = require('express'); const app = express(); app.use(express.static('./')); const socketIO = require("socket.io"); const server = http.createServer(app); server.listen(port, host, () => { console.log(`Server is running on http://${host}:${port}`); }); const io = socketIO(server, {cookie: false}); io.on('connection', (socket) => { console.log('a user connected'); socket.on("details", (chatBundle) => { // 用字符串拼接输出消息 console.log(`${chatBundle[0]}: ${chatBundle[1]}`); }); });
修正后的客户端代码
<!DOCTYPE html> <html> <body> <h1>CHAT ROOM</h1> <form onsubmit="return sendServer()"> <label for="name">Name: <input id="name" name="name" type="text"> </label> <label for="text">Message: <input id="text" name="text" type="text"> </label> <input type="submit" id="send" > </form> <!-- 使用服务端提供的相对路径加载socket.io客户端 --> <script src="/socket.io/socket.io.js"></script> <script> const chatmsg = "details"; const socket = io(); function sendServer(){ var sender = document.getElementById("name").value; // 获取输入框内容 var text = document.getElementById("text").value; // 获取输入框内容 var tempArray = [sender, text] socket.emit(chatmsg, tempArray); // 可选:提交后清空输入框 document.getElementById("name").value = ""; document.getElementById("text").value = ""; return false; }; </script> </body> </html>
验证步骤
- 安装依赖:执行
npm install express socket.io - 启动服务:运行
node 你的服务端文件名.js - 测试功能:浏览器打开
http://localhost:8000,输入姓名和消息提交,终端即可看到对应日志输出。
内容的提问来源于stack exchange,提问作者Chanson Guo
相关产品推荐
相关产品推荐

