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.

57 lines
1.7KB

  1. import { APP_BASE_HREF } from '@angular/common';
  2. import { CommonEngine } from '@angular/ssr';
  3. import express from 'express';
  4. import { fileURLToPath } from 'node:url';
  5. import { dirname, join, resolve } from 'node:path';
  6. import bootstrap from './src/main.server';
  7. // The Express app is exported so that it can be used by serverless Functions.
  8. export function app(): express.Express {
  9. const server = express();
  10. const serverDistFolder = dirname(fileURLToPath(import.meta.url));
  11. const browserDistFolder = resolve(serverDistFolder, '../browser');
  12. const indexHtml = join(serverDistFolder, 'index.server.html');
  13. const commonEngine = new CommonEngine();
  14. server.set('view engine', 'html');
  15. server.set('views', browserDistFolder);
  16. // Example Express Rest API endpoints
  17. // server.get('/api/**', (req, res) => { });
  18. // Serve static files from /browser
  19. server.get('*.*', express.static(browserDistFolder, {
  20. maxAge: '1y'
  21. }));
  22. // All regular routes use the Angular engine
  23. server.get('*', (req, res, next) => {
  24. const { protocol, originalUrl, baseUrl, headers } = req;
  25. commonEngine
  26. .render({
  27. bootstrap,
  28. documentFilePath: indexHtml,
  29. url: `${protocol}://${headers.host}${originalUrl}`,
  30. publicPath: browserDistFolder,
  31. providers: [{ provide: APP_BASE_HREF, useValue: baseUrl }],
  32. })
  33. .then((html) => res.send(html))
  34. .catch((err) => next(err));
  35. });
  36. return server;
  37. }
  38. function run(): void {
  39. const port = process.env['PORT'] || 80;
  40. // Start up the Node server
  41. const server = app();
  42. server.listen(port, () => {
  43. console.log(`Node Express server listening on http://localhost:${port}`);
  44. });
  45. }
  46. run();