我有一个 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,但无济于事。