如何解决http-proxy-middleware 异步更改标头
我在 NodeJS 中使用 http-proxy-middleware 来代理执行身份验证的 PHP 站点。
PHP 站点返回标头“saml-user-id”。
我使用这个 saml-user-id 来生成一个我想添加为 cookie 的令牌。我需要在数据库中查找用户,所以它需要异步工作。
代码如下:
// DOESN'T WORK
exports.proxySimpleSamlMiddleware = createProxyMiddleware(['/saml'],{
ssl: {
key: fs.readFileSync('/path/to/my.key'),cert: fs.readFileSync('path/to/my.crt'),},target: 'https://127.0.0.1:8443',secure: false,logLevel: 'debug',changeOrigin: true,onProxyRes: async (proxyRes,req,res) => { // <-- ASYNCHRONOUS
let tokenCookie = 'token=';
if (proxyRes.headers['saml-user-id']) {
const userId = proxyRes.headers['saml-user-id'];
const token = await getNewToken(userId);
tokenCookie = `token=${token}; path=/; httponly; samesite=lax`;
}
// Set the 'token' cookie
// (simplified,in reality I read the existing cookies from the headers
// and add this cookie to the list)
proxyRes.headers['set-cookie'] = tokenCookie;
},});
上面的代码不起作用。未更改任何标头,并且出现错误(“将标头发送到客户端后无法设置标头”)。我猜这是因为 onProxyRes 中的异步函数。
如果我把代码改成这样:
// DOESN'T WORK ASYNCHRONOUSLY
onProxyRes: (proxyRes,res) => { // <-- REMOVED ASYNC
let tokenCookie = 'token=my-new-token';
proxyRes.headers['set-cookie'] = tokenCookie;
},
然后按预期将“令牌”cookie 设置为“my-new-token”。这不是一个选项,因为我想要进行的更改是异步的。
我已经尝试过“responseIntercepter”:
// DOESN'T WORK
selfHandleResponse: true,onProxyRes: responseInterceptor(async (responseBuffer,proxyRes,res) => {
let tokenCookie = 'token=my-new-token';
proxyRes.headers['set-cookie'] = tokenCookie;
return responseBuffer;
}),
但这也不会更新“令牌”cookie。
我的问题:
有没有办法使用 http-proxy-middleware 异步更改标头?
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。