Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

enable CORS #30

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 16 additions & 4 deletions lib/proxy.js
Original file line number Diff line number Diff line change
Expand Up @@ -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');
Expand Down Expand Up @@ -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;
}

Expand All @@ -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
Expand All @@ -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 = '';
}

Expand Down