Created
March 12, 2015 18:43
-
-
Save cgmartin/6877bdb9ce1f98064e52 to your computer and use it in GitHub Desktop.
Node Proxy Example
This file contains hidden or 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
'use strict'; | |
var port = parseInt(process.env.PROXY_PORT || process.env.PORT || 8000); | |
process.env.PROXY_PORT = port; | |
process.env.STATIC_PORT = port + 1; | |
process.env.API_PORT = port + 2; | |
process.env.CHAT_PORT = port + 3; | |
require('./proxy-server'); | |
require('./static-server'); | |
require('./api-server'); | |
require('./chat-server'); |
This file contains hidden or 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
'use strict'; | |
var url = require('url'); | |
var fs = require('fs'); | |
var httpProxy = require('http-proxy'); | |
var sslCfg = require('config').get('ssl'); | |
var port = parseInt(process.env.PROXY_PORT || process.env.PORT || 8000); | |
var staticUrl = process.env.STATIC_URL || 'http://127.0.0.1:' + process.env.STATIC_PORT; | |
var apiUrl = process.env.API_URL || 'http://127.0.0.1:' + process.env.API_PORT; | |
var chatUrl = process.env.CHAT_URL || 'http://127.0.0.1:' + process.env.CHAT_PORT; | |
// | |
// Create a proxy server with custom application logic | |
// | |
var proxy = httpProxy.createProxy(); | |
// | |
// Create your custom server and just call `proxy.web()` to proxy | |
// a web request to the target passed in the options | |
// | |
var onRequest = function(req, res) { | |
var pathname = url.parse(req.url).pathname; | |
var targetUrl = staticUrl; | |
if (pathname.toLowerCase().indexOf('/api/') === 0) { | |
targetUrl = apiUrl; | |
} | |
return proxy.web(req, res, {target: targetUrl}); | |
}; | |
var server; | |
if (sslCfg.enabled) { | |
var serverOptions = { | |
key: fs.readFileSync(sslCfg.key), | |
cert: fs.readFileSync(sslCfg.cert) | |
}; | |
server = require('https').createServer(serverOptions, onRequest); | |
} else { | |
server = require('http').createServer(onRequest); | |
} | |
// You can also use `proxy.ws()` to proxy a websockets request | |
server.on('upgrade', function(req, socket, head) { | |
proxy.ws(req, socket, head, {target: chatUrl}); | |
}); | |
server.listen(port, function() { | |
console.log('proxy listening on port:', port); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment