Initializing Ws Server With Express
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
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 }`));
Related Questions
- → Maximum call stack exceeded when instantiating class inside of a module
- → Browserify api: how to pass advanced option to script
- → Node.js Passing object from server.js to external modules?
- → gulp-rename makes copies, but does not replace
- → requiring RX.js in node.js
- → Remove an ObjectId from an array of objectId
- → Can not connect to Redis
- → React: How to publish page on server using React-starter-kit
- → Express - better pattern for passing data between middleware functions
- → Can't get plotly + node.js to stream data coming through POST requests
- → IsGenerator implementation
- → Async/Await not waiting
- → (Socket.io on nodejs) Updating div with mysql data stops without showing error