From 050cbf683c24ca590fee51f15f776b8a35ea806e Mon Sep 17 00:00:00 2001 From: Benjamin Flesch Date: Thu, 23 Feb 2023 15:34:55 +0000 Subject: [PATCH] add error handling --- .../3.going-further/12.websocket-servers.md | 15 +++++++++------ 1 file changed, 9 insertions(+), 6 deletions(-) diff --git a/docs/2.guide/3.going-further/12.websocket-servers.md b/docs/2.guide/3.going-further/12.websocket-servers.md index 2d191af03d..2389990aaf 100644 --- a/docs/2.guide/3.going-further/12.websocket-servers.md +++ b/docs/2.guide/3.going-further/12.websocket-servers.md @@ -34,9 +34,13 @@ import http from 'node:http' const proxySocketIO = httpProxy.createProxyServer({ target: 'http://localhost:3001' }); const proxyNuxt = httpProxy.createProxyServer({ target: 'http://localhost:3000' }); -const proxyServer = http.createServer((req, res) => { +// error handlers needed, otherwise it would `throw err` on client connection resets +proxySocketIO.on("error", (err) => console.error("proxySocketIO error:", err)) +proxyNuxt.on("error", (err) => console.error("proxyNuxt error:", err)) + +// create http server to merge both proxies on same port +const httpServer = http.createServer((req, res) => { const isSocketIo = req.url.startsWith("/socket.io") - // choose backend depending on url if (isSocketIo) { proxySocketIO.web(req, res) @@ -46,10 +50,8 @@ const proxyServer = http.createServer((req, res) => { }) // upgrade client connection to websocket if requested -proxyServer.on('upgrade', (req, socket, head) => { +httpServer.on('upgrade', (req, socket, head) => { const isSocketIo = req.url.startsWith("/socket.io") - - // choose backend depending on url if (isSocketIo) { proxySocketIO.ws(req, socket, head) } else { @@ -57,7 +59,8 @@ proxyServer.on('upgrade', (req, socket, head) => { } }) -proxyServer.listen(4000, () => console.log("proxy is listening")) +// listen for incoming data +httpServer.listen(3000, () => console.log("proxy is listening")) ``` The socket.io server can very easily be created to listen on port `3001`.