1

I am building a proxy service that will forward all but one kind of a POST request to another server.
I was planning on using express-http-proxy to do this but I can't find a way to modify the POST request on the fly.
For Example:

I want to catch all POST requests to /getdata and check if they have a field called username,
if they do I want to replace it with a custom username and then forward the request to another server and then forward the response from it back to the user.

Any help is appreciated. Any package or resource would help. Thanks.

asds_asds
  • 990
  • 1
  • 10
  • 19

1 Answers1

1

I was facing a similar issue recently and ended up using http-proxy-middleware with the following config (based on this recipe):

const express = require('express');
const {createProxyMiddleware} = require('http-proxy-middleware');
const bodyParser = require('body-parser');
const app = express();
app.use(bodyParser.json());

const options = {
    target: '<your-target>',
    changeOrigin: true,
    onProxyReq: (proxyReq, req, res) => {
        if (req.path === '/getdata' && req.body && req.body.userName) {
            req.body.userName = "someOtherUser";
            const bodyData = JSON.stringify(req.body);
            proxyReq.setHeader('Content-Type', 'application/json');
            proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
            proxyReq.write(bodyData);
        }
    },
};


app.use(createProxyMiddleware(options));
app.listen(4001, () => console.log("listening ..."));

What did the trick for me was recalculating the Content-Length using this line:

proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
eol
  • 23,236
  • 5
  • 46
  • 64
  • 1
    Thanks a ton @eol, your solution worked perfectly. One thing though, How can I make a blocking API Request inside the onProxyReq function? The change in the POST body depends on the result from the request. – asds_asds Aug 21 '20 at 00:18
  • https://stackoverflow.com/questions/63515094/how-to-make-a-bocking-request-in-nodejs-inside-a-http-proxy-middleware-function Link to the question if interested, Thanks again!!. – asds_asds Aug 21 '20 at 01:01