Я пытаюсь ввести шлюз для моих микро сервисов. Я застрял в почтовом методе. Целевой сервер не получает тело запроса. Не уверен, что я делаю не так. Может кто-нибудь мне помочь. Вот код
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'));
С помощью анализатора тела я могу напечатать тело запроса, но не могу получить тело запроса на целевом сервере.
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'));