Recently participated in a frame-based load balancing forwarding node development, it uses http-proxy forwards, but the statistics need to be forwarded to the corresponding server request response status by querying the information found as follows:
const httpProxy = require('http-proxy');
http.createServer(function (req, res) {
httpProxy.web(req, res, {target: uri}, function (e) {
console.log(e);
});
}).listen(PORT);
httpProxy.createProxyServer({
changeOrigin: true,
ignorePath: true
});
httpProxy.on('proxyRes', function(proxyRes, req, res) {
let host = proxyRes.req.getHeader('host');
let path = proxyRes.req.path;
})
http-proxy can listen proxyRes event, when forwarding the request to return a response triggered the event. (When a client initiates a request, http-proxy forwarded to the corresponding target server, the target server returns the requested content, proxyRes trigger event, the end of the callback is executed, and then return to the client res)
proxyRes.req.getHeader () can obtain the header information corresponding to the header, in order to obtain a forwarding address server,
When you create a proxy server, you need to configure changeOrigin is true, the option to change the destination address of the header information. For example: client request address test.iqiyi.com , the forwarding address of the target server target.iqiyi.com , changeOrigin when set to true, host is obtained target.iqiyi.com; when set to false, host of value test.iqiyi.com
In addition to proxyRes event, http-proxy also supports proxyReq event, before forwarding the request to perform relevant callback logic. code show as below:
proxy.on('proxyReq', function(proxyReq, req, res) {
console.log("url:" + proxyReq.path);
});
ignorePath for forwarding the request, whether the request address in the original path back to the forwarding address attached.
For example: a client requests address: http://test.iqiyi.com/test , forwarding the request to the address: http://target.iqiyi.com/lib/mac/dianshiju/
- When ignorePath true, the proxy server does not add path forwarding, direct request http://target.iqiyi.com/lib/mac/dianshiju/
- When ignorePath is false, the proxy server forwards the request, additional path Uehara address, to request http://target.iqiyi.com/lib/mac/dianshiju/test
When creating a proxy server uses http-proxy, usually set ignorePath to true, forwarding requests to facilitate processing.