Skip to content

Instantly share code, notes, and snippets.

@alexcheng1982
Last active August 29, 2015 14:25
Show Gist options
  • Save alexcheng1982/154ed022f229851dde3f to your computer and use it in GitHub Desktop.
Save alexcheng1982/154ed022f229851dde3f to your computer and use it in GitHub Desktop.
NodeJS proxy server with CORS support
var connect = require('connect'),
httpProxy = require('http-proxy');
var app = connect();
var proxy = httpProxy.createProxyServer({
target: 'http://127.0.0.1:8080'
});
proxy.on('proxyReq', function(proxyReq, req, res, options) {
proxyReq.setHeader('Authorization', 'Basic YWRtaW46cGFzc3dvcmQ=');
});
proxy.on('error', function(e) {
console.log(e);
});
app.use(function(req, res, next) {
if (req.headers['origin']) {
res.setHeader('Access-Control-Allow-Origin', req.headers['origin']);
res.setHeader('Access-Control-Allow-Methods', 'POST, PUT, GET, OPTIONS, DELETE');
res.setHeader('Access-Control-Max-Age', '3600');
res.setHeader('Access-Control-Allow-Headers', 'X-Requested-With, Authorization, Content-Type');
}
if (req.method !== 'OPTIONS') {
next();
}
else {
res.end();
}
});
app.use(function(req, res) {
proxy.web(req, res);
});
app.listen(8000);
console.log('Proxy server started.')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment