Last active
January 26, 2018 02:45
-
-
Save cheton/9854d2d0f6b7a1551ad8f405d9b0a71d to your computer and use it in GitHub Desktop.
Proxy Server
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env node | |
const path = require('path'); | |
const bin = path.basename(process.argv[1]); | |
const chalk = require('chalk'); | |
const debug = require('debug')(bin); | |
const program = require('commander'); | |
const httpProxy = require('http-proxy'); | |
const defaultListenPort = 0; | |
const defaultTargetHost = 'localhost'; | |
const defaultTargetPort = 80; | |
program | |
.usage('[options]') | |
.option('--listen-port <port>', 'listen port', defaultListenPort) | |
.option('--target-host <host>', 'target host', defaultTargetHost) | |
.option('--target-port <port>', 'target port', defaultTargetPort); | |
program.on('--help', () => { | |
console.log(''); | |
console.log(' Examples:'); | |
console.log(''); | |
console.log(` $ ${bin} --listen-port 8080 --target-host 127.0.0.1 --target-port 80`); | |
}); | |
program.parse(process.argv); | |
const { listenPort, targetHost, targetPort } = program; | |
const proxy = httpProxy.createProxyServer({ | |
target: { | |
host: targetHost, | |
port: targetPort | |
}, | |
localAddress: '127.0.0.1' | |
}).listen(listenPort); | |
const proxyServerAddress = proxy._server.address(); | |
console.info(`Starting the proxy server at ${chalk.blueBright(proxyServerAddress.port)} and proxy requests to ${chalk.blueBright(`${targetHost}:${targetPort}`)}`); | |
proxy.on('proxyRes', function(proxyRes, req, res) { | |
//if (req.headers.origin) { | |
res.setHeader('access-control-allow-origin', '*'); | |
res.setHeader('access-control-allow-credentials', 'true'); | |
res.setHeader('access-control-max-age', 86400); | |
//} | |
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 (req.method === 'OPTIONS') { | |
res.send(200); | |
res.end(); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment