simple page with news from all around the globe
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

74 lines
2.2KB

  1. import 'zone.js/dist/zone-node';
  2. import { ngExpressEngine } from '@nguniversal/express-engine';
  3. import * as express from 'express';
  4. import { join } from 'path';
  5. import { AppServerModule } from './src/main.server';
  6. import { APP_BASE_HREF } from '@angular/common';
  7. import { existsSync } from 'fs';
  8. import { createProxyMiddleware, Options} from 'http-proxy-middleware';
  9. // The Express app is exported so that it can be used by serverless Functions.
  10. export function app(): express.Express {
  11. const server = express();
  12. const distFolder = join(process.cwd(), 'dist/news-demo/browser');
  13. const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index';
  14. const options: Options = {
  15. target: 'http://newsapi.org/v2',
  16. changeOrigin: true,
  17. pathRewrite: {
  18. '^/api': '',
  19. }
  20. };
  21. server.use('/api', createProxyMiddleware(options));
  22. // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  23. server.engine('html', ngExpressEngine({
  24. bootstrap: AppServerModule,
  25. }));
  26. server.set('view engine', 'html');
  27. server.set('views', distFolder);
  28. // Example Express Rest API endpoints
  29. // server.get('/api/**', (req, res) => { });
  30. // Serve static files from /browser
  31. server.get('*.*', express.static(distFolder, {
  32. maxAge: '1y'
  33. }));
  34. // All regular routes use the Universal engine
  35. server.get('*', (req, res) => {
  36. res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  37. });
  38. return server;
  39. }
  40. function run(): void {
  41. const port = process.env.PORT || 4000;
  42. // Start up the Node server
  43. const server = app();
  44. server.listen(port, () => {
  45. console.log(`Node Express server listening on http://localhost:${port}`);
  46. });
  47. }
  48. // Webpack will replace 'require' with '__webpack_require__'
  49. // '__non_webpack_require__' is a proxy to Node 'require'
  50. // The below code is to ensure that the server is run only when not requiring the bundle.
  51. declare const __non_webpack_require__: NodeRequire;
  52. const mainModule = __non_webpack_require__.main;
  53. const moduleFilename = mainModule && mainModule.filename || '';
  54. if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  55. run();
  56. }
  57. export * from './src/main.server';