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 (将#修改为@)