Ad

Initializing Ws Server With Express

- 1 answer

I have been struggling to find the source of an error in the following code:

const express = require("express");
const path = require("path");
const WebSocket = require("ws");
const SocketServer = WebSocket.Server;

const PORT = process.env.PORT || 3000; // port to listen on

const INDEX = path.join(__dirname, "index.html"); // index address

var server = express();

server.use((req, res) => res.sendFile(INDEX));
server.listen(PORT, () => console.log(`Listening on port ${ PORT }`));

const wss = new SocketServer({server}); // wss = web socket server

(I have code below for connection etc. that is irrelevant to this question I think)

Upon running this, I receive the following error from the client in the browser:

WebSocket connection to 'ws://localhost:3000/' failed: Connection closed before receiving a handshake response

What is confusing me is that the code works if I make the following change:

var server = express()
    .use((req, res) => res.sendFile(INDEX));
    .listen(PORT, () => console.log(`Listening on port ${ PORT }`));

The problem with this method is that it does not work to add in another .use before the existing .use, which is necessary for accessing static files (i.e. javascript as its own file instead of in an HTML file)

Why does changing my code between these two examples break it? What can I do to resolve this?

Thank you

Ad

Answer

I found a solution!

It turns out that you must set the value of the server variable when .use and .listen are called.

var server = express();

server = server.use((req, res) => res.sendFile(INDEX));
server = server.listen(PORT, () => console.log(`Listening on port ${ PORT }`));

instead of

var server = express();
server.use((req, res) => res.sendFile(INDEX));
server.listen(PORT, () => console.log(`Listening on port ${ PORT }`));
Ad
source: stackoverflow.com
Ad