add error handling

This commit is contained in:
Benjamin Flesch 2023-02-23 15:34:55 +00:00
parent 00d2b90ea0
commit 050cbf683c
1 changed files with 9 additions and 6 deletions

View File

@ -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`.