node.js - 当“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 请求传递回客户端。我发现自己开始实现依赖于标题内容类型的正文解析逻辑,但我非常希望有一种更简单的方法。
有任何想法吗?
解决方案
解决方法很简单...
proxyRes.pipe(res);
在源代码中找到node-http-proxy
。
推荐阅读
- reactjs - 无法解析 '...\node_modules\open\lib' 中的 'child_process'
- airflow - 气流 504 网关超时
- ftp - 为什么 SFTP 没有像 FTP 这样的主动/被动模式
- c++ - 使用前向类声明声明类对象(基本 C++)
- python - 在 Pandas 的一列中具有布尔条件 True 的 Groupby
- azure-service-fabric - FabricInvalidAddressException:尝试从 .NET Core 应用程序连接时,NamedEndpoint 'V2Listener'
- javascript - 如何使用接口在打字稿中添加两个数字
- html - 一个角度的div
- android - 从 Eclipse 到 Android Studio:由于巨大的方法导致 VFY 拒绝
- php - 方法 Illuminate\Validation\Validator::validateGt 不存在