explore-services/sample-components/sampleComponent-2/src/server.ts

71 lines
2.0 KiB
TypeScript

// 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 './main.node';
// 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}));
/* **AK** Add this path so that index.html can see files from node_modules folder (e.g. bootstrap files)*/
app.use(express.static(path.join(ROOT, 'node_modules'), {index: false}));
// app.get('/bootstrap.css', express.static(path.join(ROOT, 'node_modules/bootstrap/dist/css/bootstrap.min.css')));
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: req.hostname
});
}
// Routes with html5pushstate
// ensure routes match client-side-app
app.get('/', ngApp);
app.get('/claims', 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}`);
});