使用grunt-connect-proxy时重写cookie路径

时间:2014-08-05 11:43:29

标签: cookies proxy grunt-connect-proxy

在开发过程中,我使用grunt-connect-proxy在本地提供一些远程API。这很好用,除了我使用的重写规则不适用于cookie:

proxies: [{
  context: '/publicPath',
  host: 'localhost',
  port: 8080,
  rewrite: {
    '^/publicPath': '/privatePath'
  }
}]

如果远程API设置了包含路径/privatePath的Cookie,则必须将其重写为/publicPath

E.g。使用Apache httpd时,我会使用ProxyPassReverseCookiePath - 指令。如何使用grunt-connect-proxy进行操作?

1 个答案:

答案 0 :(得分:4)

感谢this answer in "Rewrite response headers with node-http-proxy"我设法解决了问题。我创建了以下中间件:

function rewriteSetCookie(req, res, next) {
    var isProxyRequest = req.url.lastIndexOf('/publicPath', 0) === 0;
    if (isProxyRequest) {
        // we intercept the writeHead function, so that we can exchange headers just before they are written
        var oldWriteHead = res.writeHead;
        res.writeHead = function () {
            var cookie = res.getHeader('Set-Cookie');
            if (cookie) {
                res.setHeader('Set-Cookie', cookie.map(function(item) {
                    // Replace paths in all cookies. The simple string/replace approach might be too naive in some cases, so check before you copy&paste before thinking
                    return item.replace(/\/privatePath/, '/publicPath');
                }));
            }
            oldWriteHead.apply(res, arguments);
        };
    }
    next();
}

这里仅供参考,是完整配置,以便您可以了解如何使用中间件:

connect: {
    server: {
        options: {
            hostname: 'localhost',
            base: 'myBaseDir',
            open: true,
            middleware: function (connect, options) {
                if (!Array.isArray(options.base)) {
                    options.base = [options.base];
                }

                // Setup the proxy
                var middlewares = [rewriteSetCookie, proxySnippet];
                //                 ^^^^^^^^^^^^^^^^- Here is is used!

                // Serve static files.
                options.base.forEach(function(base) {
                    middlewares.push(connect.static(base));
                });

                // Make directory browse-able.
                var directory = options.directory || options.base[options.base.length - 1];
                middlewares.push(connect.directory(directory));

                return middlewares;
            }
        },
        proxies: [{
            context: '/publicPath',
            host: 'localhost',
            port: 8080,
            rewrite: {
                '^/publicPath': '/privatePath'
            }
        }]
    }
}