Created
September 13, 2012 23:54
-
-
Save mikestead/3718736 to your computer and use it in GitHub Desktop.
Node HTTP Proxy with Express Server (same port)
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
// For cookies from proxied service to work, content and proxy must be served | |
// from same address and port, and proxy port must be < 1024 | |
var serviceSettings = { | |
host:"<service-host>", | |
port:80 | |
} | |
var serverSettings = { | |
port:98, | |
rootPath:"/public", | |
proxyPath:"/api" // e.g. http://localhost:98/api/GetUser maps to http://<service-host>/GetUser | |
} | |
var express = require('express'), | |
app = express(), | |
httpProxy = require('http-proxy'); | |
var proxy = new httpProxy.HttpProxy({target: serviceSettings}); | |
app.listen(serverSettings.port); | |
app.use(express.static(__dirname + serverSettings.rootPath)); | |
app.all(serverSettings.proxyPath + '/*',function(request, response){ | |
// Remove the proxyPath from the query string | |
request.url = '/' + request.url.split('/').slice(serverSettings.proxyPath.length - 2).join('/'); | |
if (request.method == 'OPTIONS') { | |
response.setHeader('access-control-allow-origin', request.headers.origin); | |
response.setHeader('access-control-allow-credentials', 'true'); | |
response.setHeader('access-control-allow-methods', request.method); | |
response.setHeader('access-control-allow-headers', request.headers['access-control-request-headers']); | |
response.writeHead(200); | |
response.end(); | |
} | |
else { | |
response.setHeader('Access-Control-Allow-Origin', '*'); | |
response.setHeader('Access-Control-Allow-Methods', 'GET, OPTIONS, HEAD, POST, PUT, DELETE'); | |
response.setHeader('Access-Control-Allow-Headers', 'X-Requested-With'); | |
proxy.proxyRequest(request, response); | |
} | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment