Skip to content

Instantly share code, notes, and snippets.

@hulufei
Last active October 10, 2018 09:50
Show Gist options
  • Save hulufei/256f731a43f137922eb0097f72197d89 to your computer and use it in GitHub Desktop.
Save hulufei/256f731a43f137922eb0097f72197d89 to your computer and use it in GitHub Desktop.
http-proxy with cookies and gzip responses(Solved CORS limit)
var http = require("http"),
httpProxy = require("http-proxy");
var url = require("url");
var zlib = require("zlib");
var proxy = httpProxy.createProxyServer({});
proxy.on("proxyRes", function(proxyRes, req, res) {
console.log("Proxy response");
// res.headers = proxyRes.headers;
let allowedOrigin = false;
if (req.headers.origin) {
const originHostName = url.parse(req.headers.origin).hostname;
if (originHostName) {
res.setHeader("access-control-allow-origin", req.headers.origin);
res.setHeader("access-control-allow-credentials", "true");
allowedOrigin = true;
}
}
if (req.headers["access-control-request-method"]) {
res.setHeader(
"access-control-allow-methods",
req.headers["access-control-request-method"]
);
}
if (req.headers["access-control-request-headers"]) {
res.setHeader(
"access-control-allow-headers",
req.headers["access-control-request-headers"]
);
}
if (allowedOrigin) {
res.setHeader("access-control-max-age", 60 * 60 * 24 * 30);
if (req.method === "OPTIONS") {
res.end();
}
}
// http://nickfishman.com/post/49533681471/nodejs-http-requests-with-gzip-deflate-compression
var encoding = proxyRes.headers["content-encoding"];
var onPipeError = function(e) {
console.log(`Gunzip ${req.url} error: ${e}`);
res.end();
};
console.log(req.url, "encoding", encoding);
if (encoding == "gzip") {
proxyRes.pipe(zlib.createGunzip()).on("error", onPipeError).pipe(res);
} else if (encoding == "deflate") {
proxyRes.pipe(zlib.createInflate()).on("error", onPipeError).pipe(res);
} else {
proxyRes.pipe(res);
}
});
var server = http.createServer(function(req, res) {
console.log("req cookies", req.headers.cookie);
proxy.web(req, res, {
target: "https://refundhunter.cn",
changeOrigin: true,
selfHandleResponse: true,
headers: {
cookie: req.headers.cookie || ""
}
});
});
console.log("Listening on 8090");
server.listen(8090); // See (†)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment