diff --git a/lib/proxy.js b/lib/proxy.js index 4fb49ce..fbe688b 100644 --- a/lib/proxy.js +++ b/lib/proxy.js @@ -10,7 +10,7 @@ var routers = {}, config, useGateway; -exports.initialize = function initialize(options){ +exports.initialize = function initialize(options) { logger = options.logger || require('./logger'); config = configParser(options).proxy; useGateway = (config.gateway !== null && typeof(config.gateway) === 'object' && typeof(config.gateway.host) === 'string'); @@ -105,6 +105,18 @@ function createRouter(target) { router = httpProxy.createProxyServer(options); + router.on('proxyRes', function(proxyRes, req, res) { + // valid CORS request *always* contains an Origin header + // in some cases it's present also for same-origin requests + // but it's sufficient to set CORS response headers for all such requests + if (req.headers.origin) { + res.setHeader('Access-Control-Allow-Origin', req.headers.origin); + // TODO provide option to allow custom request headers (like SOAPAction, for example) + res.setHeader('Access-Control-Allow-Headers', 'Content-Type'); + res.setHeader('Access-Control-Allow-Methods', 'HEAD,OPTIONS,GET,POST,PUT,DELETE'); + } + }); + routers[key] = router; } @@ -124,7 +136,7 @@ function injectAuthHeader(req) { // inject any custom header values into a proxy request // along with the x-forwarded-for, x-forwarded-port, and via headers -function injectProxyHeaders(req, rule){ +function injectProxyHeaders(req, rule) { // the HTTP host header is often needed by the target webserver config req.headers['host'] = rule.target.host + (rule.target.originalPort ? util.format(':%d', rule.target.originalPort) : ''); // document that this request was proxied @@ -135,11 +147,11 @@ function injectProxyHeaders(req, rule){ var value = header.value, name = header.name; - if(typeof(value) === 'function') { + if (typeof(value) === 'function') { value = value.call(undefined, req); } - if(typeof(value) !== 'string') { + if (typeof(value) !== 'string') { value = ''; }