Search code examples
javascriptwebsocketws

Can't make a websocket connection between react client and express server


I'm trying to make a connection between a react client and an express server with websockets. Every time I try this i get an error. I think I'm missing something.

Server code:

var http = require('http');
var ws = require('ws');

var theHttpServer = http.createServer();
var theWebSocketServer = new ws.Server({
    server: theHttpServer,
    verifyClient: true
});

theHttpServer.on('request', app);
theHttpServer.listen(9000,
    function () {
        console.log("The Server is lisening on port 9000.")
    });

theWebSocketServer.on('connection', function connection(msg) {
    console.log("CONNECTION CREATED");

    websocket.on('message', function incoming(message) {
    });
});

Client code:

let wsConnection = new WebSocket("ws://localhost:9000");

wsConnection.onopen = function(eventInfo) {
    console.log("Socket connection is open!");
}

The error:

if (!this.options.verifyClient(info)) return abortHandshake(socket, 401); ^

TypeError: this.options.verifyClient is not a function


Solution

  • You're passing verifyClient as a boolean, not a function. What you would maybe want to do is change this to:

    function verifyClient(info) { 
      // ...Insert your validation code here 
    };
    var theWebSocketServer = new ws.Server({
      server: theHttpServer,
      verifyClient: verifyClient
    });