NodeJS 提示:输入的文本未显示在终端中

tv6aics1  于 11个月前  发布在  Node.js
关注(0)|答案(1)|浏览(132)

Index.html

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>iChat - Realtime Node Socket.io Chat App</title>
    <script src="http://localhost:8000/socket.io/socket.io.js"></script>
    <script src="js/client.js"></script>
    <link rel="stylesheet" href="css/style.css">
</head>
<body>
    <nav>
        <img class="logo" src="chat-removebg-preview (1).png">
    </nav>
    <div class="container">
        <div class="message right">Jack : Hi Peter </div>
        <div class="message left"> Peter : Hi Jack ! how are you ?</div>

    </div>
    <div class="send">
        <form action="#" id="send-container">
            <input type="text" name="messageInp" id="messageInp">
            <button class="btn" type="submit">Send</button>
        </form>
    </div>
</body>

</html>

字符串
index.js

const { Socket } = require('socket.io');

// Node server which will handle socket io connections
const io = require('socket.io')(8000)

const users = {};

io.on('connection', Socket => {
socket.on('new-user-joined', Name => {
console.log("New user", Name)
users[socket.id] = Name;
socket.broadcast.emit('user-joined', Name)
    });

socket.on('send', message => {
socket.broadcast.emit('receive', { message: message, Name: users[socket.id] })
    });
})


client.js

const socket = io('https://localhost:8000');

const form = document.getElementById('send-container');
const messageInput = document.getElementById('messageInp')
const messageContainer = document.querySelector(".container")

const Name = prompt("Enter your name to join")
socket.emit('new-user-joined', Name)


我是从一个教程聊天网站,然后我键入这个:

const Name = prompt ("Enter your name to join") 
socket.emit ('new-user-joined', Name)


我期待我会在网站的提示区域输入任何东西的名称,它会显示在终端,但它显示在终端什么都没有,当我键入,我刷新了很多次,并使用nodemon也以确保我的代码更新

ebdffaop

ebdffaop1#

你需要一个http服务器。我没有看到你在你的代码中创建了一个http服务器。请检查官方文档。
你可以试试这个
index.js

const express = require("express");
const app = express();
const server = app.listen(8000);

app.use(express.static(__dirname));

const socketio = require("socket.io");
const io = socketio(server);

io.on("connection", (socket) => {
    socket.on("new-user-joined", data => {
        console.log(data);
    });
});

字符串
client.js

const socket = io('http://localhost:8000');
const name = prompt("Enter your name to join");
socket.emit('new-user-joined', name);


这段代码将没有任何问题。

相关问题