Home > Mobile >  Node.js server hanging on startup | Websocket connection failed
Node.js server hanging on startup | Websocket connection failed

Time:12-29

So I'm trying to host a web app using node.js express and my server.js seems to hang upon using npm start. In my package.json file it calls node server.js and everything starts properly but my website won't deploy to the local host for me to view. I have a feeling it is either something to do with the location of my css/index.html or it could be something with the way i create the request from the client side from index.html I'm new to backend, so really out in the deep on this one.

//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);

This is my index.html below

<!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>

UPDATE:

So the issue that seems to be popping up now is WebSocket connection to 'ws://localhost:2525/' failed var ws = new WebSocket(HOST); So the error is happening between the handshake between the client and server

CodePudding user response:

The 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));

The 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>
  • Related