http-proxy forwards the request response processing

Disclaimer: This article is a blogger original article, shall not be reproduced without the bloggers allowed.

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) {

    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 , the forwarding address of the target server , changeOrigin when set to true, host is obtained; when set to false, host of value

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: , forwarding the request to the address:

When creating a proxy server uses http-proxy, usually set ignorePath to true, forwarding requests to facilitate processing.

Guess you like