mirror of
https://github.com/angular/angular-cli.git
synced 2025-05-19 20:52:06 +08:00
This commit implements the capability for the App Engine to serve prerendered pages directly. Previously, we relied on frameworks like Express for this functionality, which resulted in inconsistent redirects for directories where in some cases a trailing slash was added to the route. **Note:** This change applies only when using the new SSR APIs. When using the `CommonEngine`, a 3rd party static serve middleware is still required.
67 lines
1.6 KiB
Plaintext
67 lines
1.6 KiB
Plaintext
import {
|
|
AngularNodeAppEngine,
|
|
createNodeRequestHandler,
|
|
isMainModule,
|
|
writeResponseToNodeResponse,
|
|
} from '@angular/ssr/node';
|
|
import express from 'express';
|
|
import { dirname, resolve } from 'node:path';
|
|
import { fileURLToPath } from 'node:url';
|
|
|
|
const serverDistFolder = dirname(fileURLToPath(import.meta.url));
|
|
const browserDistFolder = resolve(serverDistFolder, '../<%= browserDistDirectory %>');
|
|
|
|
const app = express();
|
|
const angularApp = new AngularNodeAppEngine();
|
|
|
|
/**
|
|
* Example Express Rest API endpoints can be defined here.
|
|
* Uncomment and define endpoints as necessary.
|
|
*
|
|
* Example:
|
|
* ```ts
|
|
* app.get('/api/**', (req, res) => {
|
|
* // Handle API request
|
|
* });
|
|
* ```
|
|
*/
|
|
|
|
/**
|
|
* Serve static files from /<%= browserDistDirectory %>
|
|
*/
|
|
app.use(
|
|
express.static(browserDistFolder, {
|
|
maxAge: '1y',
|
|
index: false,
|
|
redirect: false,
|
|
}),
|
|
);
|
|
|
|
/**
|
|
* Handle all other requests by rendering the Angular application.
|
|
*/
|
|
app.use('/**', (req, res, next) => {
|
|
angularApp
|
|
.handle(req)
|
|
.then((response) =>
|
|
response ? writeResponseToNodeResponse(response, res) : next(),
|
|
)
|
|
.catch(next);
|
|
});
|
|
|
|
/**
|
|
* Start the server if this module is the main entry point.
|
|
* The server listens on the port defined by the `PORT` environment variable, or defaults to 4000.
|
|
*/
|
|
if (isMainModule(import.meta.url)) {
|
|
const port = process.env['PORT'] || 4000;
|
|
app.listen(port, () => {
|
|
console.log(`Node Express server listening on http://localhost:${port}`);
|
|
});
|
|
}
|
|
|
|
/**
|
|
* The request handler used by the Angular CLI (dev-server and during build).
|
|
*/
|
|
export const reqHandler = createNodeRequestHandler(app);
|