[HPM] Error occurred while proxying request [ECONNRESET]

tanut aran
1 min readMay 23, 2021

--

Here is the full error thrown from http-proxy-middleware

[HPM] Error occurred while proxying request localhost:3000/foo to http://localhost:3009/ [ECONNRESET](https://nodejs.org/api/errors.html#errors_common_system_errors)

Causes

TLDR;

When sending client --> proxy --> API server

Proxy transform body to JS object and it try to proxy that JS object so it fails.

HTTP is plain text protocol it accept ‘string’ as a body.

https://github.com/chimurai/http-proxy-middleware/issues/171

Solution

Transform that parsed JS object back to JSON string i.e.

[Client]        [Proxy in]    [Proxy out]     [API server]
JSON string --> JS Object --> JSON String --> JS Object

You can do that by adding a hook supported by http-proxy-middleware lib.

options.onProxyReq = (proxyReq, req: Request, res) => {
if (!req.body || !Object.keys(req.body).length) {
return;
}
const contentType = proxyReq.getHeader('Content-Type');
const writeBody = (bodyData: string) => {
proxyReq.setHeader(
'Content-Length', Buffer.byteLength(bodyData)
);
proxyReq.write(bodyData);
};
// ADD SUPPORT FOR
// contentType: 'application/json; charset:utf-8'
if (contentType.includes('application/json')) {
writeBody(JSON.stringify(req.body));
}
if (contentType === 'application/x-www-form-urlencoded') {
writeBody(querystring.stringify(req.body));
}
}

https://github.com/chimurai/http-proxy-middleware/issues/320

--

--