升级纱线后React中的Websocket握手错误

时间:2019-12-16 19:39:14

标签: reactjs websocket

在我的react应用中,我使用websocket包(不是 socket.io)连接到一些Websockets

 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;
  }

这一直很好,实际上除了我在控制台中也收到此错误之外,仍然可以正常工作:

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

错误指向node-modules/react-dev-utils/webpackHotDevClient.js中似乎是罪魁祸首的这些行:

// 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',
  })
);

我刚运行yarn upgrade --latest --exact,所以我猜想这与它有关系。

尤其是因为我们使用控制台向客户端进行演示,所以我真的很想摆脱此错误消息。谢谢!

2 个答案:

答案 0 :(得分:8)

我们与弹出的CRA项目存在相同的问题。

我的解决方案是手动config/webpackDevServer.config.js配置文件的更新。

天哪,这是我们的livereload再次起作用的原因:

     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

答案 1 :(得分:0)

在本地主机上开发Azure门户扩展时,我遇到了同样的问题。我将“ ws”更改为“ wss”,并且有效。