Node.js 服务器在启动时挂起 | Websocket 连接失败

Node.js server hanging on startup | Websocket connection failed

所以我正在尝试使用 node.js express 托管网络应用程序,而我的 server.js 似乎无法使用 npm start。在我的 package.json 文件中它调用 node server.js 并且一切正常启动但我的网站不会部署到本地主机供我查看。我觉得这要么与我 css/index.html 的位置有关,要么与我从 index.html 从客户端创建请求的方式有关 我是后端新手,所以真的很喜欢这个。

//1.) create http server
const PORT = process.env.PORT || 2525;
const INDEX = '/public/index.html';
const express = require('express')



var server = express();
console.log(__dirname)
server.use(express.static(__dirname + "/public"));
server.get('public/index.html', function(req, res, next) {
      res.sendFile(__dirname + INDEX);
  });
server.listen(PORT);


//2.) Create a websocket server

const { Server } = require('ws');
const wss = new Server({ server });


//3.) Handle connections

wss.on('connection', (ws) => {
  console.log('Client connected');
  ws.on('close', () => console.log('Client disconnected'));
});


//4.) Boradcast updates
setInterval(() => {
  wss.clients.forEach((client) => {
    client.send(new Date().toTimeString());
  });
}, 1000);
console.log('Server started at http://localhost:' + PORT);

下面是我的index.html

<!DOCTYPE html>
<html>
<head>
  <meta charset="UTF-8">
  <meta name='viewport' content='width=device-width, initial-scale=1'>
  <title>am i sheep</title>
  <link rel="stylesheet" href="css/style.css" type="text/css">
</head>
<body>

  <div>
    <span>
      <h3> Am I Sheep<h3>
    </span>
  </div>

  <div>
  </div>
  <div>
        <input type="file" id="fileID" hidden></input>
        <label for='fileID'>select image</label>
  </div>

  <div>
    <h1 id='server-time'>current time</h1>
    <script>
    var HOST = location.origin.replace(/^http/, 'ws')
    var ws = new WebSocket(HOST);
    var el;

    ws.onmessage = function (event) {
      el = document.getElementById('server-time');
      el.innerHTML = 'Server time: ' + event.data;
    };
    </script>
  </div>
</body>
</html>

更新:

所以现在似乎突然出现的问题是 WebSocket connection to 'ws://localhost:2525/' failed var ws = new WebSocket(HOST); 所以错误发生在客户端和服务器之间的握手

server.js

//1.) create http server
const PORT = process.env.PORT || 2525;
const INDEX = "/public/index.html";
const express = require("express");
const { createServer } = require("http");

const app = express();
const httpServer = createServer(app);

// Static files
app.use(express.static(__dirname + "/public"));
app.get("/", function (req, res, next) {
  res.sendFile(__dirname + INDEX);
});

//2.) Create a websocket server
const { Server } = require("ws");
const wss = new Server({ server: httpServer });

//3.) Handle connections
wss.on("connection", ws => {
  console.log("Client connected");
  ws.on("close", () => console.log("Client disconnected"));
});

//4.) Boradcast updates
setInterval(() => {
  wss.clients.forEach(client => {
    client.send(new Date().toTimeString());
  });
}, 1000);

httpServer.listen(PORT, () => console.log("Server started at http://localhost:" + PORT));

index.html

<!DOCTYPE html>
<html>

<head>
    <meta charset="UTF-8">
    <meta name='viewport' content='width=device-width, initial-scale=1'>
    <title>am i sheep</title>
    <link rel="stylesheet" href="css/style.css" type="text/css">
</head>

<body>

    <div>
        <span>
            <h3> Am I Sheep<h3>
        </span>
    </div>

    <div>
    </div>
    <div>
        <input type="file" id="fileID" hidden></input>
        <label for='fileID'>select image</label>
    </div>

    <div>
        <h1 id='server-time'>current time</h1>
        <script>
            var HOST = location.origin.replace(/^http/, 'ws')
            var ws = new WebSocket(HOST);
            var el;

            ws.onopen = function () {
                alert('Connection Open');
            };

            ws.onerror = function (error) {
                alert('Error');
            };

            ws.onmessage = function (event) {
                el = document.getElementById('server-time');
                el.innerHTML = 'Server time: ' + event.data;
            };
        </script>
    </div>
</body>

</html>