首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用grunt连接代理时重写cookie路径

使用grunt连接代理时重写cookie路径
EN

Stack Overflow用户
提问于 2014-08-05 11:43:28
回答 1查看 2.2K关注 0票数 1

在开发过程中,我使用grunt-connect代理使一些远程API在本地可用。这很好,只是我使用的重写规则没有应用于cookie:

代码语言:javascript
复制
proxies: [{
  context: '/publicPath',
  host: 'localhost',
  port: 8080,
  rewrite: {
    '^/publicPath': '/privatePath'
  }
}]

如果远程API使用路径/privatePath设置cookie,则必须将其重写为/publicPath

例如,当使用Apache时,我会使用ProxyPassReverseCookiePath-Directive。我怎么用咕噜-连接-代理来做呢?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-08-05 11:43:28

多亏了这个答案出现在“用节点-http-代理重写响应头”中。,我才弄明白了这一点。我创建了以下中间件:

代码语言:javascript
复制
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();
}

仅供参考,这里是完整的配置,这样您就可以看到如何使用中间件:

代码语言:javascript
复制
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'
            }
        }]
    }
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/25137981

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档