Skip to content

Instantly share code, notes, and snippets.

@fluxsaas
Last active August 29, 2015 14:02
Show Gist options
  • Save fluxsaas/f829067ef7b570a61276 to your computer and use it in GitHub Desktop.
Save fluxsaas/f829067ef7b570a61276 to your computer and use it in GitHub Desktop.
example proxy config.ru to foreward ajax request to different domain (CORS - workaround)
# Rack app to proxy ajax request to server on different domain (CORS).
# This is usefull if you have a rails-api and a backbone frontend on different domains
# and you want an easy solution to develop both apps on your local mashine with pow.
# Put this file in your backbone/angular/javascript folder.
# The assets should be in the ./public folder
# extend the REGEX to match a path you want to redirect.
# @redirect_regex = /\/api/
# change the API url
# @api_url = 'example.com'
require 'logger'
require 'rack-proxy'
require 'json'
class AppProxy < Rack::Proxy
def initialize
super
@logger = Logger.new('./log/rack.log')
@api_url = 'example.com'
@redirect_regex = /\/api/
end
def log(string)
@logger.info("#{string}")
end
def env_log env
log "#{env['REQUEST_METHOD']} #{env['PATH_INFO']}"
end
def api_url(env)
subdomain = env['HTTP_HOST'].split(".").first
url = "#{subdomain}.#{@api_url}"
return url
end
def rewrite_env(env)
env_log env
match = env["PATH_INFO"].match @redirect_regex
if match && match.length > 0
env["HTTP_HOST"] = api_url(env)
end
env
end
end
run AppProxy.new
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment