Skip to content

Instantly share code, notes, and snippets.

@supersonictw
Forked from sintaxi/server.js
Last active April 26, 2024 12:21
Show Gist options
  • Save supersonictw/cf01a30ed886c8763bdd8329c1115f8c to your computer and use it in GitHub Desktop.
Save supersonictw/cf01a30ed886c8763bdd8329c1115f8c to your computer and use it in GitHub Desktop.
Easy CORS/Reverse Proxy
#!/usr/bin/env node
// Easy CORS/Reverse Proxy
// License: MIT (https://ncurl.xyz/s/RD0Yl5fSg)
// https://gist.github.com/supersonictw/cf01a30ed886c8763bdd8329c1115f8c
"use strict";
const cookieEncoder = (data) => {
const cookies = [];
for (const key in data) {
const value = encodeURIComponent(data[key]);
cookies.push(`${key}=${value}`);
}
return cookies.join("; ");
};
const config = {
connection: {
scheme: 'https',
host: 'example.com',
},
reqOrigin: 'https://example.com',
resOrigin: 'http://example.com',
extendReqHeaders: {
cookie: cookieEncoder({
lang: "en",
}),
"x-requested-with": "ECRP",
},
extendResHeaders: {
"x-powered-by": "ECRP",
},
};
const http = require("node:http");
const https = require("node:https");
http.createServer((req, rsp) => {
const options = {
...config.connection,
path: req.url,
method: req.method,
headers: {
...req.headers,
host: config.connection.host,
origin: config.reqOrigin,
referer: config.reqOrigin,
connection: "close",
...config.extendReqHeaders
},
port: config.connection.port ||
(config.connection.scheme === 'https' ? 443 : 80),
};
const client = config.connection.scheme === 'https' ? https : http;
const proxy = client.request(options, (response) => {
rsp.writeHead(response.statusCode, {
...response.headers,
"access-control-allow-origin": config.resOrigin,
"access-control-allow-credentials": "true",
...config.extendResHeaders
});
response.on("data", (chunk) => {
rsp.write(chunk);
});
response.on("end", () => {
rsp.end();
});
});
proxy.once("error", (e) => {
console.error(e);
rsp.writeHead(500);
rsp.end();
});
req.pipe(proxy);
req.on('end', () => {
proxy.end()
});
}).listen(8000);
console.info("Proxy server running at http://localhost:8000/");
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment