Last active
October 9, 2016 13:25
-
-
Save matthieu-D/9d4595d02a91b977f15eece27f5131d1 to your computer and use it in GitHub Desktop.
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
// the polyfills must be the first thing imported in node.js | |
import 'angular2-universal-polyfills'; | |
import * as path from 'path'; | |
import * as express from 'express'; | |
import * as bodyParser from 'body-parser'; | |
import * as cookieParser from 'cookie-parser'; | |
// Angular 2 | |
import { enableProdMode } from '@angular/core'; | |
// Angular 2 Universal | |
import { createEngine } from 'angular2-express-engine'; | |
// App | |
import { MainModule } from './app.node.module.ts'; | |
// enable prod for faster renders | |
enableProdMode(); | |
const app = express(); | |
const ROOT = path.join(path.resolve(__dirname, '..')); | |
// Express View | |
app.engine('.html', createEngine({})); | |
app.set('views', __dirname); | |
app.set('view engine', 'html'); | |
app.use(cookieParser('Angular 2 Universal')); | |
app.use(bodyParser.json()); | |
// Serve static files | |
app.use('/assets', express.static(path.join(__dirname, 'assets'), {maxAge: 30})); | |
app.use(express.static(path.join(ROOT, 'dist/client'), {index: false})); | |
import { serverApi } from './backend/api'; | |
// Our API for demos only | |
app.get('/data.json', serverApi); | |
function ngApp(req, res) { | |
res.render('index', { | |
req, | |
res, | |
ngModule: MainModule, | |
preboot: false, | |
baseUrl: '/', | |
requestUrl: req.originalUrl, | |
originUrl: 'http://localhost:3000' | |
}); | |
} | |
// Routes with html5pushstate | |
// ensure routes match client-side-app | |
app.get('/', ngApp); | |
app.get('/about', ngApp); | |
app.get('/about/*', ngApp); | |
app.get('/home', ngApp); | |
app.get('/home/*', ngApp); | |
app.get('*', function(req, res) { | |
res.setHeader('Content-Type', 'application/json'); | |
var pojo = { status: 404, message: 'No Content' }; | |
var json = JSON.stringify(pojo, null, 2); | |
res.status(404).send(json); | |
}); | |
// Server | |
let server = app.listen(process.env.PORT || 3000, () => { | |
console.log(`Listening on: http://localhost:${server.address().port}`); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment