1

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.

Sam
  • 13
  • 4
  • How is proxy breaking? Do you get error messages? If so, what errors do you get? – Geshode Sep 15 '22 at 05:23
  • When I am hitting the endpoint like POST http://localhost:3602 with JSON body, the API becomes unresponsive – Sam Sep 15 '22 at 05:38
  • You should probably add `proxy.on('error', function(e) {...});` to see, if an error is returned. As described [here](https://github.com/http-party/node-http-proxy#core-concept). – Geshode Sep 15 '22 at 05:43
  • I added callback error section, but do not see any error. Maybe somehow target API is not responding? not sure whats going on. – Sam Sep 15 '22 at 06:12
  • Do you have access to the target API and can see, if the endpoints are being reached? – Geshode Sep 15 '22 at 07:04
  • In my target Node apps, I commented out bodyParser and now I am getting response in proxy, but there is no req body in the target apps. – Sam Sep 15 '22 at 07:46
  • Likely this is due to the fact that if you want the body, you have to disable `bodyParser`. You then have to handle the response manually, but it seems no one can figure out how to do this – lots of open tickets about the issue. – brandonscript Feb 27 '23 at 02:55

0 Answers0