5

I am using http-proxy on node.js. I have a proxy request to another server. my requirement is that the proxy request should timeout in 10 seconds. Also when the time out happens, I should be able to display a custom message to user

I have the below code

var proxy = new httpProxy.RoutingProxy();
  req.on('error', function (err,req,res){
       res.send("An error occured");
  });
  proxy.proxyRequest(req, res, {
    host: 'localhost',
    port: port,
    headers:req.headers,
    timeout:10000
  })  

This sets the timeout (due to reasons not known, it times out in 17 secs) but the callback is never executed. It just shows the standard browser message

The connection was reset
          The connection to the server was reset while the page was loading.

Thanks in advance

UPDATE:

I tried

proxy.on('proxyError', function (err,preq,pres) {
    pres.writeHead(500, { 'Content-Type': 'text/plain' });
    pres.write("An error happened at server. Please contact your administrator.");
    pres.end();
  });

This time the method gets invoked, but it complains that the response is already sent, so cannot set headers

Srijit
  • 475
  • 7
  • 30

1 Answers1

3

You may want to try this :

proxy.on('error', function(err, preq, pres){     
    pres.writeHead(500, { 'Content-Type': 'text/plain' });
    pres.write("An error happened at server. Please contact your administrator.");
    pres.end();
});   
FacePalm
  • 10,992
  • 5
  • 48
  • 50