我正在运行一个开发代理服务器,在启动时我会使用我们的集群架构请求一个授权 token 。
但是,此 token 会在一段时间后过期。然后,我不想让开发人员重新启动他们的代理服务器,而是想发出另一个请求以获取另一个有效的身份验证 token 。为了能够自己处理响应,我将 node-http-proxy
选项 selfHandleResponse
设置为 true。
app.use(
'/',
index({
target: config.hostname,
changeOrigin: true,
onProxyReq,
onProxyRes,
selfHandleResponse: true
})
);
现在,我只想处理带有 401
的响应,因为这是我唯一需要请求另一个 token 的情况。
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 请求传递回客户端。我发现自己开始根据 header 内容类型实现正文解析逻辑,但我非常希望有更简单的方法。
有什么想法吗?
最佳答案
解决方法很简单……
proxyRes.pipe(res);
在node-http-proxy
的源码中找到。
关于node.js - 当 'selfHandleResponse' 为真时,如何传递代理响应?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55612745/