ws: Error: unexpected server response (200)

I’m trying to connect as a socket client to a socket server with this code:

let socket = new WebSocket('wss://' + serverConfig['host'] + ':' + serverConfig['port'] + '/some/uri', {
    perMessageDeflate: false,
    rejectUnauthorized: false, // Server is self-signed for reasons.
});

In this specific instance, the host is 192.168.0.57 and the port is 443. Unfortunately, it throws this error:

Error: unexpected server response (200)
    at ClientRequest._req.on (/var/www/html/node_modules/ws/lib/WebSocket.js:650:26)
    at emitOne (events.js:96:13)
    at ClientRequest.emit (events.js:188:7)
    at HTTPParser.parserOnIncomingClient [as onIncoming] (_http_client.js:473:21)
    at HTTPParser.parserOnHeadersComplete (_http_common.js:99:23)
    at TLSSocket.socketOnData (_http_client.js:362:20)
    at emitOne (events.js:96:13)
    at TLSSocket.emit (events.js:188:7)
    at readableAddChunk (_stream_readable.js:176:18)
    at TLSSocket.Readable.push (_stream_readable.js:134:10)

This is baffling, since I’m basically being told that it’s an error that the response was OK. I hope there’s something wrong with my request, but the error message is utterly uninformative.

About this issue

  • Original URL
  • State: closed
  • Created 7 years ago
  • Comments: 21 (7 by maintainers)

Most upvoted comments

maybe you can try it: location / { proxy_pass http://127.0.0.1:3030; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; }

nginx config done!

I got it working by switching libraries. I don’t think there’s anything wrong with this one, just some other piece to my larger puzzle. I hate to close this without a full explanation. Thanks!

has someone fixed the issue?

just remove the following line const WebSocket = require(‘ws’); in browser code and you will be happy.

Your server is not handling the handshake properly. It answers to the upgrade request as it was a normal request. Make sure that you are hitting the WebSocket server.