简体   繁体   中英

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!

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

I had the same issue when developing an azure portal extension on my localhost. I changed 'ws' to 'wss' and it worked.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM