[英]Chat message not logging nodejs
Aim: To make the chat message the user entered to appear in the console (terminal).目的:使用户输入的聊天消息显示在控制台(终端)中。 It currently isn't logging anything and I don't know how to debug this problem.它目前没有记录任何东西,我不知道如何调试这个问题。 Please keep in mind that I'm a beginner to NodeJS and know probably only the basics.请记住,我是 NodeJS 的初学者,可能只了解基础知识。
Server-side NodeJS code服务器端 NodeJS 代码
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");
// creating the server and starting it on port 8000
const server = http.createServer(app);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
// making io object
const io = socketIO(server, {cookie: false});
// listening to connections to the server
io.on('connection', (socket) => {
console.log('a user connected');
// chat message coming to server
socket.on("details", (chatBundle) => {
console.log(join(chatBundle[0], ": ", chatBundle[1]));
});
});
Client-side HTML code客户端 HTML 代码
<!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>
<script src="/Users/chanson/node_modules/socket.io/client-dist/socket.io.js">
</script>
<script>
const chatmsg = "details"; // added
const socket = io(); // added
function sendServer(){
var sender = document.getElementById("name");
var text = document.getElementById("text");
var tempArray = [sender, text]
socket.emit(chatmsg, tempArray)
return false; // added
};
</script>
</body>
</html>
Please help me debug this code.请帮我调试这段代码。
in your client file import the socket.io like this:在您的客户端文件中导入 socket.io,如下所示:
<script src="/socket.io/socket.io.js">
instead of代替
<script src="/Users/chanson/node_modules/socket.io/client-dist/socket.io.js">
as by default, the Socket.IO server exposes a client bundle at /socket.io/socket.io.js.默认情况下,Socket.IO 服务器在 /socket.io/socket.io.js 公开一个客户端包。
Also make sure you are hosting the client file from you server's static resources or other wise like so:还要确保您从服务器的 static 资源或其他方式托管客户端文件,如下所示:
// creating the server and starting it on port 8000
app.get('/', (req, res)=>{
res.sendFile(path.join(__dirname, 'public', 'index.html'))
})
const server = http.createServer(app);
server.listen(port, host, () => {
console.log(`Server is running on http://${host}:${port}`);
});
Also in you client file's sendServer
function correct the following lines:同样在您的客户端文件的sendServer
function 中更正以下行:
var sender = document.getElementById("name").value;
var text = document.getElementById("text").value;
use.value to capture the user input use.value 捕获用户输入
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.