1+ import type { IncomingMessage } from 'node:http' ;
2+ import { styleText } from 'node:util' ;
3+
14import { Debug } from '../../debug.js' ;
25import type { Plugin } from '../../types.js' ;
36import { definePlugin } from '../define-plugin.js' ;
47
58const debug = Debug . extend ( 'debug-proxy-errors-plugin' ) ;
69
10+ const BODY_PARSER_ERROR_MESSAGE = `[HPM] Connection reset (ECONNRESET) detected with non-empty "req.body [ERR_HPM.GH40]".
11+
12+ This usually means that the request body (req.body) was already parsed before reaching the proxy.
13+ When bodyParser runs first, it consumes the request stream, leaving the proxy unable to forward the body data to the target server.
14+
15+ How to fix this issue:
16+ - Option 1: Place the proxy middleware before the bodyParser middleware.
17+ - Option 2: Use 'fixRequestBody()' helper to fix this issue.
18+
19+ For more details, see: https://github.com/chimurai/http-proxy-middleware/issues/40\n` ;
20+
21+ function hasParsedBody ( req : IncomingMessage | undefined ) : boolean {
22+ return Boolean ( req && req . method === 'POST' && 'body' in req && req . body ) ;
23+ }
24+
725/**
826 * Subscribe to {@link https://github.com/unjs/httpxy#events `httpxy` error events} to prevent server from crashing.
927 * Errors are logged with {@link https://www.npmjs.com/package/debug debug} library.
@@ -16,6 +34,11 @@ export const debugProxyErrorsPlugin: Plugin = definePlugin((proxyServer, options
1634 */
1735 proxyServer . on ( 'error' , ( error , req , res , target ) => {
1836 debug ( `httpxy error event: \n%O` , error ) ;
37+
38+ // detect request body (when bodyParser used) and log an error message to help debugging
39+ if ( ( error as any ) . code === 'ECONNRESET' && hasParsedBody ( req ) ) {
40+ console . error ( styleText ( 'red' , BODY_PARSER_ERROR_MESSAGE ) ) ;
41+ }
1942 } ) ;
2043
2144 proxyServer . on ( 'proxyReq' , ( proxyReq , req , socket ) => {
0 commit comments