2

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

gkd
  • 853
  • 1
  • 14
  • 31
  • Please fix some things on your code and let us know if the problem continue. First remove the extra `}` causing syntax error. Also remove the duplicated line `const jsonParser = BodyParser.json();` The `target` option need to know its protocol so try with: `http://127.0.0.1:7800` Even if this works fine, your code is in a context where req.body wont exist – Daniel Aristizabal Sep 13 '17 at 17:25
  • @DanielAristizabal Thanks, I have made syntax fixes. – gkd Sep 14 '17 at 05:15

1 Answers1

2

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);
});
  • Thanks Daniel, but above code is giving same output (undefined) and app.use(BodyParse()) actually hangs the route - all apis in front end getting timeout – gkd Sep 14 '17 at 05:23
  • I'd think the problem could be versions missmatch. Check version compatibility betweem express and the body parsing plugin used, a hang is caused by not calling `next()` in the middleware chain. Double check the documentation of the body parsing plugin maybe should be calling it in a different way. If you POST data to /api should be show on `req.body` and proxy response is show on `data`. – Daniel Aristizabal Sep 16 '17 at 15:09