|
| 1 | +import { |
| 2 | + AngularNodeAppEngine, |
| 3 | + createNodeRequestHandler, |
| 4 | + isMainModule, |
| 5 | + writeResponseToNodeResponse, |
| 6 | +} from '@angular/ssr/node'; |
| 7 | +import express from 'express'; |
| 8 | +import { join } from 'node:path'; |
| 9 | + |
| 10 | +const browserDistFolder = join(import.meta.dirname, '../browser'); |
| 11 | + |
| 12 | +const app = express(); |
| 13 | +const angularApp = new AngularNodeAppEngine(); |
| 14 | + |
| 15 | +/** |
| 16 | + * Example Express Rest API endpoints can be defined here. |
| 17 | + * Uncomment and define endpoints as necessary. |
| 18 | + * |
| 19 | + * Example: |
| 20 | + * ```ts |
| 21 | + * app.get('/api/{*splat}', (req, res) => { |
| 22 | + * // Handle API request |
| 23 | + * }); |
| 24 | + * ``` |
| 25 | + */ |
| 26 | + |
| 27 | +/** |
| 28 | + * Serve static files from /browser |
| 29 | + */ |
| 30 | +app.use( |
| 31 | + express.static(browserDistFolder, { |
| 32 | + maxAge: '1y', |
| 33 | + index: false, |
| 34 | + redirect: false, |
| 35 | + }), |
| 36 | +); |
| 37 | + |
| 38 | +/** |
| 39 | + * Handle all other requests by rendering the Angular application. |
| 40 | + */ |
| 41 | +app.use((req, res, next) => { |
| 42 | + angularApp |
| 43 | + .handle(req) |
| 44 | + .then((response) => |
| 45 | + response ? writeResponseToNodeResponse(response, res) : next(), |
| 46 | + ) |
| 47 | + .catch(next); |
| 48 | +}); |
| 49 | + |
| 50 | +/** |
| 51 | + * Start the server if this module is the main entry point. |
| 52 | + * The server listens on the port defined by the `PORT` environment variable, or defaults to 4000. |
| 53 | + */ |
| 54 | +if (isMainModule(import.meta.url)) { |
| 55 | + const port = process.env['PORT'] || 4000; |
| 56 | + app.listen(port, (error) => { |
| 57 | + if (error) { |
| 58 | + throw error; |
| 59 | + } |
| 60 | + |
| 61 | + console.log(`Node Express server listening on http://localhost:${port}`); |
| 62 | + }); |
| 63 | +} |
| 64 | + |
| 65 | +/** |
| 66 | + * Request handler used by the Angular CLI (for dev-server and during build) or Firebase Cloud Functions. |
| 67 | + */ |
| 68 | +export const reqHandler = createNodeRequestHandler(app); |
0 commit comments