为什么用户名未定义?如果我将Id =“ name”(“ nam”更改为“ name')?

时间:2019-12-11 01:50:55

标签: node.js express socket.io

我用node express socket.io创建了一个简单的Messenger Web应用程序。 但是用户名的结果是不确定的。(如果我更改用户ID,则可以使用,但是为什么?)
app.js

const app = express();
const http = require("http").createServer(app);
const io = require("socket.io")(http);

app.use(express.static(__dirname + "/"));

io.on("connection", socket => {
  console.log("connected", socket.id);

  socket.on("chat", data => {
    console.log(data.name);

    io.sockets.emit("chat", data);
  });
});

http.listen("3000", () => {
  console.log("messenger is on!");
});

index.html

<body class="container">
    <div id="input">
        <input type="text" id="nam" placeholder="what is your name?" />         // user name
        <input type="text" id="message" placeholder="type your message..." />
        <button onclick="clicked()" type="submit" class="btn btn-success" id="send">
            send
        </button>
    </div>
    <div id="contener">
        <div id="output"></div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.dev.js"></script>
    <script>
        var socket = io();

        var nam = document.getElementById("nam");
        var message = document.getElementById("message");
        var send = document.getElementById("send");
        var output = document.getElementById("output");

        function clicked() {
            socket.emit("chat", {
                name: nam.value,
                message: message.value
            });
        }
        socket.on("chat", data => {
            output.innerHTML += `<p>${data.name} <br> ${data.message}</p>`;
        });
    </script>
</body>

如果我将所有“ nam” 更改为“ name” ,那么它将无法正常工作!为什么?

我不知道怎么了。 尝试一下,将所有 nam 替换为 name

1 个答案:

答案 0 :(得分:1)

a busy cat 只需将所有 nam 替换为 name

<body class="container">
    <div id="input">
        <input type="text" id="name" placeholder="what is your name?" />
        <input type="text" id="message" placeholder="type your message..." />
        <button onclick="clicked()" type="submit" class="btn btn-success" id="send">
            send
        </button>
    </div>
    <div id="contener">
        <div id="output"></div>
    </div>
    <script src="https://cdnjs.cloudflare.com/ajax/libs/socket.io/2.3.0/socket.io.dev.js"></script>
    <script>
        var socket = io();

        var name = document.getElementById("name");
        var message = document.getElementById("message");
        var send = document.getElementById("send");
        var output = document.getElementById("output");

        function clicked() {
            socket.emit("chat", {
                name: name.value,
                message: message.value
            });
        }
        socket.on("chat", data => {
            output.innerHTML += `<p>${data.name} <br> ${data.message}</p>`;
        });
    </script>
</body>