Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Websocket handshake error in React after yarn upgrade

In my react app, I connect to some websockets using the websocket package (not socket.io)

 componentDidMount(): void {
    this.settingsSubscription = subscribeToWebsocket("Settings", urls.SETTINGS_WS, handleSettingsMessage);
    this.statusSubscription = subscribeToWebsocket("Status", urls.STATUS_WS, handleStatusMessage);
    this.studyDataSubscription = subscribeToWebsocket("Study Data", urls.STUDY_WS, handleStudyDataMessage);
  }

  subscribeToWebsocket(name, url, messageHandler): W3CWebSocket {
    let subscription = new W3CWebSocket(url);
    subscription.onopen = () => console.log(`WebSocket Client Connected (${name})`);
    subscription.onclose = () => console.log(`WebSocket Client Disconnected (${name})`);
    subscription.onmessage = messageHandler;
    return subscription;
  }

This had been working fine, and in fact does still work fine except I also get this error in the console:

WebSocket connection to 'ws://localhost:3000/sockjs-node' failed: 
Error during WebSocket handshake: Unexpected response code: 200

./node_modules/react-dev-utils/webpackHotDevClient.js   @   webpackHotDevClient.js:51
__webpack_require__ @   bootstrap:785
fn  @   bootstrap:150
1   @   helpers.ts:1
__webpack_require__ @   bootstrap:785
checkDeferredModules    @   bootstrap:45
webpackJsonpCallback    @   bootstrap:32
(anonymous) @   index.chunk.js:1

The error points to these lines in node-modules/react-dev-utils/webpackHotDevClient.js which appear to be the culprit:

// Connect to WebpackDevServer via a socket.
var connection = new WebSocket(
  url.format({
    protocol: 'ws',
    hostname: window.location.hostname,
    port: window.location.port,
    // Hardcoded in WebpackDevServer
    pathname: '/sockjs-node',
  })
);

I had just run yarn upgrade --latest --exact so I'm guessing that has something or other to do with it.

Especially since we use the console to demo to the client, I'd really love to get rid of this error message. Thanks!

like image 488
Jonathan Tuzman Avatar asked Dec 16 '19 19:12

Jonathan Tuzman


1 Answers

we had same issue with ejected CRA project.

Solution of mine is manual update of the config/webpackDevServer.config.js config file.

Imho this changes are the reason our livereload works again:

     hot: true,
+    // Use 'ws' instead of 'sockjs-node' on server since we're using native
+    // websockets in `webpackHotDevClient`.
+    transportMode: "ws",
+    // Prevent a WS client from getting injected as we're already including
+    // `webpackHotDevClient`.
+    injectClient: false,
     // It is important to tell WebpackDevServer to use the same "root" path
like image 178
hromada.dan Avatar answered Sep 28 '22 00:09

hromada.dan