我正在尝试为我的微服务引入网关。我陷入了张贴方法。目标服务器未收到请求正文。不知道我在做什么错。谁能帮我吗。这是代码
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'));