首页 > 解决方案 > 当“selfHandleResponse”为真时,如何传递代理响应?

问题描述

我正在运行一个开发代理服务器,在启动时我使用我们的集群架构请求身份验证令牌。

但是,此令牌会在一段时间后过期。然后,我不想让开发人员重新启动他们的代理服务器,而是提出另一个请求来获取另一个有效的身份验证令牌。为了能够自己处理响应,我将node-http-proxy选项设置selfHandleResponse为 true。

app.use(
  '/',
  index({
    target: config.hostname,
    changeOrigin: true,
    onProxyReq,
    onProxyRes,
    selfHandleResponse: true
  })
);

现在,我只想处理带有 a 的响应401,因为这是我需要请求另一个令牌的唯一情况。

const onProxyRes = (proxyRes, req, res) => {
  if (proxyRes.statusCode === 401) {
    getToken()
      .then(forwardRequest(req))
      .then((response) => {
        res.send(response.body);
      })
      .catch(() => {        
        res.sendStatus(500);
      });
  }

  // How to pass back the original proxyRes including body, headers etc.?
});

编辑: forwardRequest 是我重试原始请求的功能,然后在成功时将其交给客户端。

我的麻烦从这里开始,因为我不知道如何将代理的非 401 请求传递回客户端。我发现自己开始实现依赖于标题内容类型的正文解析逻辑,但我非常希望有一种更简单的方法。

有任何想法吗?

标签: node.jsexpressrequestnode-http-proxyhttp-proxy-middleware

解决方案


解决方法很简单...

proxyRes.pipe(res);

在源代码中找到node-http-proxy


推荐阅读