Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

node.js http-proxy how to set timeout and a handler on request

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

like image 343
Srijit Avatar asked Oct 22 '22 07:10

Srijit


1 Answers

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();
});   
like image 139
FacePalm Avatar answered Oct 27 '22 10:10

FacePalm