【问题标题】:http-proxy-middleware: return custom error instead of proxying the requesthttp-proxy-middleware:返回自定义错误而不是代理请求
【发布时间】:2018-03-14 10:18:31
【问题描述】:

http-proxy-middleware Nodejs 模块提供了一种使用 option.router 参数中的函数重新定位请求的方法。如here所述:

router: function(req) {
    return 'http://localhost:8004';
}

我需要实现一个过程来检查请求中的某些方面(标头、URL...所有这些信息都在函数接收的req 对象中)并在某些情况下返回 404 错误。像这样的:

router: function(req) {
    if (checkRequest(req)) {
        return 'http://localhost:8004';
    }
    else {
        // Don't proxy and return a 404 to the client
    }
}

但是,我不知道如何解决 // Don't proxy and return a 404 to the client。寻找 http-proxy-middleware 并不那么明显(或者至少我还没有找到方法......)。

欢迎对此提供任何帮助/反馈!

【问题讨论】:

    标签: node.js http-proxy-middleware


    【解决方案1】:

    您可以在onProxyReq 中执行此操作,而不是抛出和捕获错误:

    app.use('/proxy/:service/', proxy({
        ...
        onProxyReq: (proxyReq, req, res) => {
            if (checkRequest(req)) {
                // Happy path
                ...
                return target;
            } else {
                res.status(404).send();
            }
        }
    }));
    

    【讨论】:

      【解决方案2】:

      最后我已经解决了 throwing 和 expection 问题,并使用了默认的 Express 错误处理程序(我在问题帖子中没有提到,但代理存在于基于 Express 的应用程序中)。

      类似这样的:

      app.use('/proxy/:service/', proxy({
              ...
              router: function(req) {
                  if (checkRequest(req)) {
                      // Happy path
                      ...
                      return target;
                  }
                  else {
                      throw 'awfull error';
                  }
              }
      }));
      
      ...
      
      // Handler for global and uncaugth errors
      app.use(function (err, req, res, next) {
          if (err === 'awful error') {
              res.status(404).send();
          }
          else {
              res.status(500).send();
          }
          next(err);
      });
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2017-08-21
        • 2023-03-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-12-13
        • 1970-01-01
        • 2021-04-08
        相关资源
        最近更新 更多