Angular SSR file server.ts and file main.server.ts

Discussão em 'Angular' iniciado por Max, Fevereiro 14, 2025.

  1. Max

    Max Guest

    I am using Angular SSR version 19. On the official Angular website https://angular.dev/api/ssr/node/CommonEngineRenderOptions they write that:

    Note: In Angular v17 and later, server.ts is no longer used by ng serve. The dev server will use main.server.ts directly to perform server side rendering.

    When I create a project, two files server.ts and main.server.ts appear in the project. The server.ts file contains the code:

    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, '../browser');

    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 /browser
    */
    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);


    And how to use the main.server.ts file is not entirely clear because it is empty. I copied the entire code from the server.ts file and pasted it into the main.server.ts file and it does not work. I do not know why. Please tell me what I am doing wrong? I am trying to make the main.server.ts file work as it is said on the official website:

    Note: In Angular v17 and later, server.ts is no longer used by ng serve. The dev server will use main.server.ts directly to perform server side rendering.

    Continue reading...

Compartilhe esta Página