代理的 websocket 连接立即关闭

Proxied websocket connection is immediately closed

我有一个 create-react-app 开发服务器代理后端连接(就像一个一样)。突然 websocket 代理停止工作。

我的 setupProxy.js 看起来像这样:

const proxy = require('http-proxy-middleware');

module.exports = function(app) {
  const port = process.env.BACKEND_PORT || '8080';
  const target = `http://localhost:${port}`;
  app.use(proxy(['/path/to/socket'], {
    target,
    ws: true,
    onProxyReqWs: function(proxyReq, req, socket) {
      socket.on('error', err => console.log(err));
      console.log('socket is destroyed', socket.destroyed)
    },
    logLevel: 'debug',
  }));

  app.use(proxy(shouldProxy, {
    target,
    logLevel: 'debug',
  }));

(其中 shouldProxy 是一个函数,因为我关于何时代理的逻辑是......非常重要)。

当浏览器(Firefox 71 或 Chrome 79)创建一个 websocket 连接时,我可以看到后端收到请求并正常响应,但浏览器收到 400 Bad request 和 dev-server控制台有这个:

[HPM] GET /path/to/socket -> http://localhost:8080
socket is destroyed true
[HPM] Upgrading to WebSocket
Error [ERR_STREAM_DESTROYED]: Cannot call write after a stream was destroyed
    at Socket.Writable.write (_stream_writable.js:321:17)
    at ClientRequest.<anonymous> ([...]/node_modules/http-proxy/lib/http-proxy/passes/ws-incoming.js:143:14)
    at ClientRequest.emit (events.js:305:20)
    at Socket.socketOnData (_http_client.js:508:11)
    at Socket.emit (events.js:305:20)
    at addChunk (_stream_readable.js:341:12)
    at readableAddChunk (_stream_readable.js:316:11)
    at Socket.Readable.push (_stream_readable.js:250:10)
    at TCP.onStreamRead (internal/stream_base_commons.js:186:23) {
  code: 'ERR_STREAM_DESTROYED'
}
[HPM] Client disconnected

所以某些东西似乎在代理过程的早期就破坏了套接字,但我无法理解是什么。

我目前 运行 使用节点 13.5.0、http-proxy 1.18.0 和 http-proxy-middleware 0.20.0;我已经尝试将节点降级到 12.14.0 并将 HPM 降级到 0.19.1,但无济于事。

这是 an issue with create-react-app 3.3.0, caused by this bug in webpack-dev-server。将 "webpack-dev-server": "3.10.1" 添加到 package.jsonresolutions 部分并将 SKIP_PREFLIGHT_CHECK=true 添加到 .env 修复它。