Node HTTP Proxy: Trying a different endpoint based on response

412 views Asked by At

In short, we're using https://github.com/chimurai/http-proxy-middleware and if the initial proxied endpoint returns a 404 or 500, we'd like to lead the request to a different endpoint instead.

i.e.

-> http://www.example.com (404)

-> http://www.backup.com (200)

So the client receives a response from www.backup.com.

1

There are 1 answers

0
shaochuancs On BEST ANSWER

After some investigation, I find it's impossible to lead the HTTP request to another endpoint, using http-proxy-middleware.

http-proxy-middleware is powered by node-http-proxy and it's impossible to implement the requirement in node-http-proxy. The related code is listed below:

// node_modules/http-proxy/lib/http-proxy/passes/web-incoming.js
proxyReq.on('response', function(proxyRes) {
  if(server) { server.emit('proxyRes', proxyRes, req, res); }
  ...
  proxyRes.pipe(res);
});

Once the response is received, an event proxyRes is emitted, and that response is immediately piped to browser (res object).

Although we can listen proxyRes event and know the response status is 404 or 500, there is nothing we can do to change the response itself.

To implement the requirement, you need to write the proxy logic yourself, or use some other proxy module which support resonse-interception.