【问题标题】:Websocket handshake error in React after yarn upgrade纱线升级后React中的Websocket握手错误
【发布时间】:2020-04-09 07:21:57
【问题描述】:

在我的 react 应用程序中,我使用 websocket 包 (not 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,所以我猜这与它有关。

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

【问题讨论】:

  • 这很奇怪...您是在客户端和开发服务器之间还是在客户端和您自己的套接字服务器之间使用某种代理?
  • 我不这么认为!而且我认为除了升级我的软件包之外我没有改变任何东西。这个错误在今天之前没有发生。
  • Web 套接字不应响应 HTTP 200。它返回 200 的原因之一是 Web 套接字和客户端之间的代理服务器配置错误。因此,这可能是 webpack 开发服务器中的问题,或者发生了其他事情。

标签: reactjs websocket


【解决方案1】:

我们在退出 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

【讨论】:

  • 添加transportMode & injectClient可以解决websocket问题,但是HMR不行
  • 谢谢,我这两天一直在寻找解决问题的方法!
【解决方案2】:

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

【讨论】:

    猜你喜欢
    • 2020-08-17
    • 2018-11-26
    • 2019-08-03
    • 1970-01-01
    • 2019-08-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多