Parse request body and determine proxy target NodeJS http-proxy

441 Views Asked by At

Due to a use case, I am trying to first parse request body and then decide the proxy target. But whenever I am parsing req body, proxy does not work. it just becomes unresponsive. I tried bodyparser and reading from buffer as well, but any try to do anything with body is making proxy break. Here is a sample code I am using,

const express = require('express');
const httpProxy = require('http-proxy');

// Create a proxy and listen on port 3000
const proxy = httpProxy.createProxyServer({});
const app = express();

app.post('*', async function(req, res) {
  
    const buffers = [];
    for await (const chunk of req) {
        buffers.push(chunk);
      }
      const data = Buffer.concat(buffers).toString();
      console.log(JSON.parse(data)); 
      let bodyData = JSON.parse(data);

      if(bodyData.description.indexOf("payment")>-1){
        proxy.web(req, res, { target: 'http://localhost:3600/payment' });
      }else{
        proxy.web(req, res, { target: 'http://localhost:3601/order' });
      }
  
});
const server = app.listen(3602);

targets are both localhost as well as external hosts.

Really appreciate any help.

0

There are 0 best solutions below