gpt4 book ai didi

reactjs - yarn 升级后 React 中的 Websocket 握手错误

转载 作者:行者123 更新时间:2023-12-03 15:18:52 25 4
gpt4 key购买 nike

在我的 react 应用程序中,我使用 websocket 连接到一些 websockets包(不是 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;
}

这一直工作正常,实际上仍然可以正常工作,但我也在控制台中收到此错误:
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 配置文件。

恕我直言,这个变化是我们的 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

关于reactjs - yarn 升级后 React 中的 Websocket 握手错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59363237/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com