http-proxy-middleware, how to copy all/cookie headers

Avi picture Avi · Aug 15, 2016 · Viewed 12.9k times · Source

I am using lite server by John Papa with HTTP proxy middleware by chimurai as a dev server. the problem is with my session cookie, I cannot persist the session cookie that comes from the real server. I saw this solution: https://github.com/chimurai/http-proxy-middleware/issues/78

but I see no resemblance to my bs-config.js:

var proxy = require('http-proxy-middleware');

module.exports = {
    port: 3003,
    server: {
        middleware: {
            1: proxy('demo/webservice/jaxrs', {
                target: 'https://localhost:8443',
                secure: false, // disable SSL verification
                changeOrigin: true   // for vhosted sites, changes host header to match to target's host
            }),
            2: require('connect-history-api-fallback')({index: '/index.html', verbose: true})
        }
    }
};

Does someone knows how to merge this two?

UPDATE: this is part of the response headers:

set-cookie:JSESSIONID=620083CD7AEB7A6CC5772AC800E673E3; Path=/appServer/webservice/jaxrs; Secure
strict-transport-security:max-age=31622400; includeSubDomains
Transfer-Encoding:chunked

UPDATE2: I think my config should look like this:

var proxy = require('http-proxy-middleware');

function relayRequestHeaders(proxyReq, req) {
    Object.keys(req.headers).forEach(function (key) {
        proxyReq.setHeader(key, req.headers[key]);
    });
};

function relayResponseHeaders(proxyRes, req, res) {
    Object.keys(proxyRes.headers).forEach(function (key) {
            res.append(key, proxyRes.headers[key]);
        });
};

module.exports = {
    port: 3003,
    server: {
        middleware: {
            1: proxy('/skybox', {
                target: 'https://localhost:8443',
                secure: false, // disable SSL verification
                changeOrigin: true,   // for vhosted sites, changes host header to match to target's host
                onProxyReq: relayRequestHeaders,
                onProxyRes: relayResponseHeaders
            }),
            2: require('connect-history-api-fallback')({index: '/index.html', verbose: true})
        }
    }
};

but now res.append is undefined :(

Answer

B.Ma picture B.Ma · Oct 25, 2016

try it:

var cookie;
function relayRequestHeaders(proxyReq, req) {
  if (cookie) {
    proxyReq.setHeader('cookie', cookie);
  }
};

function relayResponseHeaders(proxyRes, req, res) {
  var proxyCookie = proxyRes.headers["set-cookie"];
  if (proxyCookie) {
    cookie = proxyCookie;
  }
};

It's working with lite-server