I am trying to introduce gateway for my micro services. I got stuck in post method. Target server not receiving the request body. Not sure what i am doing wrong. Can any one help me out. Here is the code
const express = require('express');
const app = express();
const httpProxy = require('http-proxy');
const apiProxy = httpProxy.createProxyServer();
const server1 = 'http://localhost:4000',
server2 = 'http://localhost:4001';
apiProxy.on('proxyReq', (proxyReq, req) => {
console.log(' in proxy req ...');
if (req.body) {
const bodyData = JSON.stringify(req.body);
// incase if content-type is application/x-www-form-urlencoded -> we need to change to application/json
proxyReq.setHeader('Content-Type','application/json');
proxyReq.setHeader('Content-Length', Buffer.byteLength(bodyData));
// stream the content
proxyReq.write(bodyData);
apiProxy.web(req,res, {target: server2});
}
});
app.all('/service1/*', (req,res) => {
console.log("redirecting to server1 ...");
apiProxy.web(req,res, {target: server1});
})
app.all('/service2/*', (req,res) => {
console.log(" req, body : ", req.body);
apiProxy.web(req,res, {target: server2});
})
apiProxy.on('error', (err,req,res) => {
console.log('got an error : ',err)
});
apiProxy.on('proxyRes', (proxyRes,req,res) => {
console.log(' got a response from the server ..');
return proxyRes;
})
app.listen(3000, () => console.log(' proxy running on 3000'));
By using the body parser i am able to print request body but not getting the request body on the target server.
const app = express();
const httpProxy = require('http-proxy');
const apiProxy = httpProxy.createProxyServer();
const server1 = 'http://localhost:4000',
server2 = 'http://localhost:4001';
const bodyParser = require('body-parser');
app.use(bodyParser.urlencoded({
extended: true
}));
app.use(bodyParser.json());
app.all('/service1/*', (req,res) => {
console.log("redirecting to server1 ...");
apiProxy.web(req,res, {target: server1});
})
app.all('/service2/*', (req,res) => {
console.log(" req, body : ", req.body);
apiProxy.web(req,res, {target: server2});
})
apiProxy.on('error', (err,req,res) => {
console.log('got an error : ',err)
});
apiProxy.on('proxyRes', (proxyRes,req,res) => {
console.log(' got a response from the server ..');
return proxyRes;
})
app.listen(3000, () => console.log(' proxy running on 3000'));