簡體   English   中英

Node.js 服務器在啟動時掛起 | Websocket 連接失敗

[英]Node.js server hanging on startup | Websocket connection failed

因此,我嘗試使用 node.js express 托管 web 應用程序,而我的 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);

這是我的索引。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); 所以錯誤發生在客戶端和服務器之間的握手之間

您的 node js 服務器是否開始在終端中正常運行?

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM