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

2024-01-10

在我的 React 应用程序中,我使用以下命令连接到一些 Websocketswebsocket包裹 (not套接字.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;
  }

这一直工作正常,事实上仍然工作正常,除了我还在控制台中收到此错误:

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所以我猜这与它有某种关系。

特别是因为我们使用控制台向客户端演示,我真的很想摆脱这个错误消息。谢谢!


我们对被驱逐的 CRA 项目也有同样的问题。

我的解决方案是手动更新config/webpackDevServer.config.js https://github.com/facebook/create-react-app/blob/master/packages/react-scripts/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
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

纱线升级后 React 中的 Websocket 握手错误 的相关文章

随机推荐