Last active
September 24, 2017 10:01
-
-
Save BransonGitomeh/93c635301e5ed1f04f44526f285fb504 to your computer and use it in GitHub Desktop.
host multiple express apps on single route
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
import morgan from 'morgan'; | |
import bodyParser from 'body-parser'; | |
import express from 'express'; | |
import debug from 'debug'; | |
import { | |
ifError | |
} from 'assert'; | |
// apps exported from their directories | |
import chichi from '../chichi/main' | |
import orbital from '../orbital/main' | |
const app = express(); | |
app.use(morgan(':method :url :status :res[content-length] - :response-time ms')) | |
function allowCrossDomain(req, res, next) { | |
res.header('Access-Control-Allow-Origin', '*'); | |
res.header('Access-Control-Allow-Methods', 'GET,POST,OPTIONS'); | |
res.header( | |
'Access-Control-Allow-Headers', | |
'Content-Type,Authorization,Content-Length,X-Requested-With', | |
); | |
if (req.method === 'OPTIONS') { | |
res.send(); | |
} else { | |
next(); | |
} | |
}; | |
app.use(allowCrossDomain); | |
// define the apps and thier routes | |
var Apps = { | |
'/chichi': chichi, | |
'/orbital_hr': orbital_hr | |
}; | |
// route to display apps endpoints | |
app.get('/', function(req, res) { | |
res.json(Object.keys(Apps)); | |
}) | |
// app routes go in as separate middleware, that can have nested middleware, meaning all the apps will function as normal | |
// you could use dynamic require startements if you please, or import like me | |
for (var k in Apps) { | |
app.use(k, Apps[k]); | |
} | |
const port = process.env.PORT || 2001 | |
const listener = app.listen(port, (err) => { | |
ifError(err); | |
debug('app:expressServer')(`Server started all apps successfully on ${listener.address().port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment