Created
July 23, 2015 14:58
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
/** | |
* Module dependencies. | |
*/ | |
var express = require('express'); | |
var https = require('https'); | |
var path = require('path'); | |
var fs = require('fs'); | |
var httpProxy = require('http-proxy'); | |
//Solution for forwarding from http to https taken from | |
//http://stackoverflow.com/questions/15801014/how-to-use-node-http-proxy-for-http-to-https-routing | |
var proxyOptions = { | |
changeOrigin: true | |
}; | |
//Only way I can find to stop the server from crashing when you reload the page too fast is to override the method throwing an exception. | |
httpProxy.prototype.onError = function (err) { | |
console.log(err); | |
}; | |
var apiProxy = httpProxy.createProxyServer(proxyOptions); | |
var apiForwardingUrl = process.env.API_URL || 'https://beta.sonder.io'; | |
var buildFolder = process.env.BUILD_DIR || 'dev-build'; | |
var server = express(); | |
// all environments | |
server.set('port', process.env.PORT || 3000); | |
//Lets you use server.put() and server.delete(). Without this you can only user server.post() and server.get(). | |
server.use(require('method-override')()); | |
//Make the public folder the context root | |
server.use(express.static(path.join(__dirname, buildFolder))); | |
//Forward API requests | |
console.log('Forwarding API requests to ' + apiForwardingUrl); | |
server.all("/auth/*", function(req, res) { | |
apiProxy.web(req, res, {target: apiForwardingUrl}); | |
}); | |
server.all("/api/*", function(req, res) { | |
apiProxy.web(req, res, {target: apiForwardingUrl}); | |
}); | |
//This is needed to use the body of a post request. | |
//This needs to come after the forwarding to apiProxy | |
//server.use(()); | |
var bodyParser = require('body-parser'); | |
server.use(bodyParser.json()); | |
server.use(bodyParser.urlencoded({ | |
extended: true | |
})); | |
//Setup endpoints | |
server.get('/*', function(req, res) { | |
res.sendFile(path.join(__dirname, buildFolder + "/index.html")); | |
}); | |
var options = { | |
key: fs.readFileSync('server/server.key'), | |
cert: fs.readFileSync('server/server.crt'), | |
requestCert: false, | |
rejectUnauthorized: false | |
}; | |
//Start Server | |
https.createServer(options, server).listen(server.get('port'), function() { | |
console.log('Express server listening on port ' + server.get('port')); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment