Himmel
Himmel

Reputation: 3709

Modify node-http-proxy request body

I'm using node-http-proxy to try and proxy a request in my node/express web server. I'm attempting to append a body to a particular request at the route level, but the response I'm getting is indicating that the req.body doesn't exist.

const proxy = httpProxy.createProxyServer({
    changeOrigin: true,
    target: process.env.API_URL,
    port: 80
});


server.post('/api/login_check', (req, res) => {
    req.url = req.url.replace('/api', '');
    req.headers['Content-Type'] = 'application/json';
    req.headers['accept'] = 'application/json';
    req.body = JSON.stringify({
        username: process.env.USERNAME,
        password: process.env.PASSWORD
    });
    proxy.web(req, res);
});

Is this possible to do at the route level with node-http-proxy?

Upvotes: 0

Views: 5808

Answers (1)

Bahi Hussein
Bahi Hussein

Reputation: 461

if i understood you correctly.

  • proxy.web can work on route level as long as you are passing req and res object
  • you can change the body on an incoming request on the proxy event

proxy.on('proxyReq', function(proxyReq, req, res, options) {
  //her you can create condition identifying your path
  if(req.body && req.url == "/user" && req.method=="POST"){
    let bodyData = JSON.stringify(req.body);
    proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
    // Stream the content
    proxyReq.write(bodyData);

  }
});

Upvotes: 1

Related Questions