why req.body is undefined in 'proxyRes'

2k Views Asked by At

Below is my code

import { createProxyServer } from 'http-proxy';
import BodyParser from 'body-parser';

const jsonParser = BodyParser.json();
const proxy = createProxyServer({
  target: 'http://127.0.0.1:7800',
  proxyTimeout: 1000,
});

app.use('/api', (req, res) => {
  proxy.web(req, res);
});

proxy.on('proxyRes', (proxyRes, req, res) => {

  proxyRes.on('data', (dataBuffer) => {
    console.log('req.body ', req.body);
    const data = dataBuffer.toString('utf8');
    console.log(data);
  });

});

I am getting req.body as undefined

If I use middleware jsonParser in app.post(..) then this routes hangs and I get timeout error in front end. code is below.

app.use('/api', jsonParser, (req, res) => {
  proxy.web(req, res);
});

I want to make logs of response & request when res.statusCode !== 200

1

There are 1 best solutions below

2
On

After some clean up of the code (remove } extra, remove duplicate line) I was able to get some runnable code, not sure if this is what you are looking for. I hope this help.

const proxy = createProxyServer({
  target: 'http://127.0.0.1:7800',
  proxyTimeout: 1000,
});

app.use(BodyParser())

app.use('/api', (req, res) => {
  proxy.on('proxyRes', (proxyRes) => {
    proxyRes.on('data', (dataBuffer) => {
      console.log('req.body ', req.body);
      const data = dataBuffer.toString('utf8');
      console.log(data);
    });
  });
  proxy.web(req, res);
});