0

I'm using expressjs to create and API. I also have a proxy server to direct requests to my API Server, as follows:

But on the API server the body of POST and PUT requests are unable to parse and the server hungs.

// on proxy server
const httpProxy = require('http-proxy');
const proxy = httpProxy.createProxyServer({});

app.all('/api/*', function(req, res){
    proxy.web(req, res, { target: 'http://example.com:9000' });
});
proxy.on('proxyReq', function(proxyReq, req, res, options) {
    if ((req.method == "POST" || req.method == "PUT") && req.body) {
        proxyReq.write(JSON.stringify(req.body));
        proxyReq.end();
    }
});

proxy.on('proxyRes', function(proxyRes, req, res) {
    var body = '';
    proxyRes.on('data', function(chunk) {
        body += chunk;
    });

    proxyRes.on('end', function() {

    });
});

Part of the api server to parse body content.

// on api server
app.use(bodyParser.json({ }));
app.use(bodyParser.urlencoded({ extended: true }));

app.use(cookieParser());
app.use(compress());
app.use(methodOverride());

I realized it hungs in the bodyParser() middleware.

Any help will be greatly appreciated. I tried various solution already on stackoverflow and none has worked for me.

Kxng Kombian
  • 467
  • 4
  • 13

1 Answers1

0

I suspect that you might have forgotten to send back the response from the api server to proxy server. If that's the case then proxy server request will hang forever waiting for a response. Inside your api route handler, please make sure that you're calling res.send()method.

I was able to run your example on my machine and after sending the response back to the proxy server it works. On my api server, this is what I have:

app.use(bodyParser.json({ }));
app.use(bodyParser.urlencoded({ extended: true }));
app.use(cookieParser());

app.all('/*',(req,res)=> {
    res.send(req.body);
});
const server = http.createServer(app);
server.listen(9000);

Then, on my proxy server, I have added the middleware for cookie and json content type information parsing.

const proxy = httpProxy.createProxyServer({});
const proxyApp = express();
proxyApp.use(bodyParser.json({}));
proxyApp.use(bodyParser.urlencoded({ extended: true }));
proxyApp.use(cookieParser());

proxyApp.all('/api/*', function(req, res){
    proxy.web(req, res, { target: 'http://localhost:9000' });
});

proxy.on('proxyReq', function(proxyReq, req, res, options) {
    if((req.method === 'POST' || req.method === 'PUT') && req.body){
        proxyReq.write(JSON.stringify(req.body));
        proxyReq.end();
    }
});

const proxyServer = http.createServer(proxyApp);
proxyServer.listen(8000);
proxyServer.on('listening',() => {
    console.log('Proxy server listening on port:8000');
});