Socket.io聊天应用未在DOM中显示消息

时间:2019-06-17 13:22:38

标签: jquery socket.io

我正在关注关于socket.io的教程。但是我无法打印到dom。

我尝试使用香草javascript而不是JQuery,但是它也不起作用。

服务器文件

var app = require('express')();
var http = require('http').Server(app);
var PORT = process.env.PORT || 3000;
var io = require('socket.io')(http);

app.get('/', function(req, res) {
    res.sendFile(__dirname + '/index.html');
});

io.on('connection', function(socket) {
    socket.on('chat message', function(msg) {
        console.log('message: ' + msg);
        io.emit('chat message' + msg);
    });
});

http.listen(PORT, function() {
    console.log("Magic is happening on http://localhost:" + PORT );
})

HTML文件

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

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Socket test</title>
    <style>
      * { margin: 0; padding: 0; box-sizing: border-box; }
      body { font: 13px Helvetica, Arial; }
      form { background: #000; padding: 3px; position: fixed; bottom: 0; width: 100%; }
      form input { border: 0; padding: 10px; width: 90%; margin-right: .5%; }
      form button { width: 9%; background: rgb(130, 224, 255); border: none; padding: 10px; }
      #messages { list-style-type: none; margin: 0; padding: 0; }
      #messages li { padding: 5px 10px; }
      #messages li:nth-child(odd) { background: #eee; }
    </style>
</head>

<body>
    <h2>Chat</h2>
    <ul id="messages"></ul>
    <form action="">
        <input id="m" autocomplete="off" />
        <button>Send</button>
    </form>


    <script src="/socket.io/socket.io.js"></script>
    <script src="https://code.jquery.com/jquery-3.4.1.js" integrity="sha256-WpOohJOqMqqyKL9FccASB9O0KwACQJpFTUBLTYOVvVU=" crossorigin="anonymous"></script>

    <script>
        $(function() {
            var socket = io();
            $('form').submit(function() {
                socket.emit('chat message', $('#m').val());
                $('#m').val('');
                return false;
            });
            socket.on('chat message', function(msg) {
                $('#messages').append($('<li>').text(msg));
                window.scrollTo(0, document.body.scrollHeight);
            });
        });
    </script>
</body>

</html>

结果应在DOM中显示一条消息。

但是我只能在终端中看到该消息。

我想念什么?

0 个答案:

没有答案