Skip to content

Instantly share code, notes, and snippets.

@robianmcd robianmcd/server.js

Created Jul 23, 2015
What would you like to do?
* 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
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) {
var apiProxy = httpProxy.createProxyServer(proxyOptions);
var apiForwardingUrl = process.env.API_URL || '';
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 and server.get().
//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
var bodyParser = require('body-parser');
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
You can’t perform that action at this time.