Skip to content

Commit c2426d1

Browse files
authoredJul 14, 2022
fix: server.proxy ws error causes crash (#9123)
1 parent d12d469 commit c2426d1

File tree

1 file changed

+23
-9
lines changed
  • packages/vite/src/node/server/middlewares

1 file changed

+23
-9
lines changed
 

‎packages/vite/src/node/server/middlewares/proxy.ts

+23-9
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type * as http from 'node:http'
2+
import type * as net from 'node:net'
23
import httpProxy from 'http-proxy'
34
import type { Connect } from 'types/connect'
45
import type { HttpProxy } from 'types/http-proxy'
@@ -43,16 +44,29 @@ export function proxyMiddleware(
4344
}
4445
const proxy = httpProxy.createProxyServer(opts) as HttpProxy.Server
4546

46-
proxy.on('error', (err, req, res) => {
47-
config.logger.error(`${colors.red(`http proxy error:`)}\n${err.stack}`, {
48-
timestamp: true,
49-
error: err
50-
})
51-
res
52-
.writeHead(500, {
53-
'Content-Type': 'text/plain'
47+
proxy.on('error', (err, req, originalRes) => {
48+
// When it is ws proxy, res is net.Socket
49+
const res = originalRes as http.ServerResponse | net.Socket
50+
if ('req' in res) {
51+
config.logger.error(
52+
`${colors.red(`http proxy error:`)}\n${err.stack}`,
53+
{
54+
timestamp: true,
55+
error: err
56+
}
57+
)
58+
res
59+
.writeHead(500, {
60+
'Content-Type': 'text/plain'
61+
})
62+
.end()
63+
} else {
64+
config.logger.error(`${colors.red(`ws proxy error:`)}\n${err.stack}`, {
65+
timestamp: true,
66+
error: err
5467
})
55-
.end()
68+
res.end()
69+
}
5670
})
5771

5872
if (opts.configure) {

0 commit comments

Comments
 (0)
Please sign in to comment.