Files
itc.webengineering/demo/src/server.ts

69 lines
1.6 KiB
TypeScript
Raw Normal View History

2025-12-06 11:38:19 +01:00
import {
AngularNodeAppEngine,
createNodeRequestHandler,
isMainModule,
writeResponseToNodeResponse,
} from '@angular/ssr/node';
2025-12-06 08:46:55 +01:00
import express from 'express';
2025-12-06 11:38:19 +01:00
import { join } from 'node:path';
2025-12-06 08:46:55 +01:00
2025-12-06 11:38:19 +01:00
const browserDistFolder = join(import.meta.dirname, '../browser');
2025-12-06 08:46:55 +01:00
const app = express();
2025-12-06 11:38:19 +01:00
const angularApp = new AngularNodeAppEngine();
2025-12-06 08:46:55 +01:00
/**
* Example Express Rest API endpoints can be defined here.
* Uncomment and define endpoints as necessary.
*
* Example:
* ```ts
2025-12-06 11:38:19 +01:00
* app.get('/api/{*splat}', (req, res) => {
2025-12-06 08:46:55 +01:00
* // Handle API request
* });
* ```
*/
/**
* Serve static files from /browser
*/
2025-12-06 11:38:19 +01:00
app.use(
2025-12-06 08:46:55 +01:00
express.static(browserDistFolder, {
maxAge: '1y',
2025-12-06 11:38:19 +01:00
index: false,
redirect: false,
2025-12-06 08:46:55 +01:00
}),
);
/**
* Handle all other requests by rendering the Angular application.
*/
2025-12-06 11:38:19 +01:00
app.use((req, res, next) => {
angularApp
.handle(req)
.then((response) =>
response ? writeResponseToNodeResponse(response, res) : next(),
)
.catch(next);
2025-12-06 08:46:55 +01:00
});
/**
2025-12-06 11:38:19 +01:00
* Start the server if this module is the main entry point, or it is ran via PM2.
2025-12-06 08:46:55 +01:00
* The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
*/
2025-12-06 11:38:19 +01:00
if (isMainModule(import.meta.url) || process.env['pm_id']) {
2025-12-06 08:46:55 +01:00
const port = process.env['PORT'] || 4000;
2025-12-06 11:38:19 +01:00
app.listen(port, (error) => {
if (error) {
throw error;
}
2025-12-06 08:46:55 +01:00
console.log(`Node Express server listening on http://localhost:${port}`);
});
}
2025-12-06 11:38:19 +01:00
/**
* Request handler used by the Angular CLI (for dev-server and during build) or Firebase Cloud Functions.
*/
export const reqHandler = createNodeRequestHandler(app);