当 'selfHandleResponse' 为真时,如何传递代理响应?
How can I pass a proxied response when 'selfHandleResponse' is true?
我是 运行 开发人员 proxy-server,在启动时我使用我们的集群架构请求授权令牌。
但是,此令牌会在一段时间后过期。然后,我不想让开发人员重新启动他们的 proxy-server,而是发出另一个请求以获取另一个有效的身份验证令牌。为了能够自己处理响应,我将 node-http-proxy
选项 selfHandleResponse
设置为 true。
app.use(
'/',
index({
target: config.hostname,
changeOrigin: true,
onProxyReq,
onProxyRes,
selfHandleResponse: true
})
);
现在,我只想处理带有 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 请求传递回客户端。我发现自己开始实现 body 依赖于 header content-type 的解析逻辑,但我非常希望有更简单的方法。
有什么想法吗?
解决方法很简单...
proxyRes.pipe(res);
在node-http-proxy
的源代码中找到。
我是 运行 开发人员 proxy-server,在启动时我使用我们的集群架构请求授权令牌。
但是,此令牌会在一段时间后过期。然后,我不想让开发人员重新启动他们的 proxy-server,而是发出另一个请求以获取另一个有效的身份验证令牌。为了能够自己处理响应,我将 node-http-proxy
选项 selfHandleResponse
设置为 true。
app.use(
'/',
index({
target: config.hostname,
changeOrigin: true,
onProxyReq,
onProxyRes,
selfHandleResponse: true
})
);
现在,我只想处理带有 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 请求传递回客户端。我发现自己开始实现 body 依赖于 header content-type 的解析逻辑,但我非常希望有更简单的方法。
有什么想法吗?
解决方法很简单...
proxyRes.pipe(res);
在node-http-proxy
的源代码中找到。