Error occurred while proxying request

[HPM] Error occurred while proxying request [ECONNRESET]

Web development Jul 14, 2023

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.
[HPM] Error occurred while trying to proxy request · Issue #171 · chimurai/http-proxy-middleware
Expected behavior make proxy request Actual behavior make proxy request unstable Setup http-proxy-middleware: 0.17.1 server: webpack -dev-server: 2.3.0 proxy middleware configuration https://gist.g…

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));
  }
}
app.use(bodyParser.json()) breaks http-proxy-middleware for HTTP POST JSON with express · Issue #320 · chimurai/http-proxy-middleware
For a test case of the following curl -X POST --header ‘Content-Type: application/json’ --header ‘Accept: text/html’ -d ’{ ”$class”: “org.accordproject.cicero.contract.AccordContractState”, “stateI…

Tags

TeamCMD

We are CODEMONDAY team and provide a variety of content about Business , technology, and Programming. Let's enjoy it with us.