node.js http-proxy 如何根据请求设置超时和处理程序

标签 node.js node-http-proxy

我在 node.js 上使用 http-proxy。我有一个到另一台服务器的代理请求。我的要求是代理请求应在 10 秒内超时。此外,当超时发生时,我应该能够向用户显示自定义消息

我有下面的代码

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

这会设置超时(由于未知原因,它会在 17 秒后超时),但永远不会执行回调。它只是显示标准的浏览器消息

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

提前致谢

更新:

我试过了

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();
  });

这次该方法被调用,但它提示说响应已经发送,所以无法设置 header

最佳答案

你可能想试试这个:

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();
});   

关于node.js http-proxy 如何根据请求设置超时和处理程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17177513/

相关文章:

javascript - 合并客户端/服务器端模板引擎

node.js - 使用 http-proxy 与 node.js 进行负载平衡

javascript - 如何使用 node-http-proxy 抑制来自目标的 301 重定向?

node.js - NodeJS HTTP 代理 - 添加 header 并更新请求 URL

node.js - Mongoose:使用更新功能时如何对结果列表进行排序

node.js - 如何处理在单个服务器上运行的多个应用程序?

javascript - 快速路由触发 : "Can' t set headers after they are sent.“错误

node.js - 创建 React App 未安装,显示错误并中止安装

node.js - 如何使用 node-http-proxy 进行 HTTP 到 HTTPS 的路由?

node.js - 使用node-http-proxy,通过proxyRequest更改url