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.

7
  • How is proxy breaking? Do you get error messages? If so, what errors do you get? Commented Sep 15, 2022 at 5:23
  • When I am hitting the endpoint like POST localhost:3602 with JSON body, the API becomes unresponsive Commented Sep 15, 2022 at 5:38
  • You should probably add proxy.on('error', function(e) {...}); to see, if an error is returned. As described here. Commented Sep 15, 2022 at 5:43
  • I added callback error section, but do not see any error. Maybe somehow target API is not responding? not sure whats going on. Commented Sep 15, 2022 at 6:12
  • Do you have access to the target API and can see, if the endpoints are being reached? Commented Sep 15, 2022 at 7:04

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.