Angular 通用服务器端呈现 (SSR) res.render 未加载

Angular Universal Server Side Rendering (SSR) res.render not loading

我正在尝试将 SSR 添加到我的网站,但未加载内容。我正在使用 Angular Universal,我按照这个 guide 进行初始配置。 http://localhost:4200/ 加载未完成,未显示任何错误。 http://localhost:4200/index.html 正在返回空视图。

构建过程成功。

server.ts

import 'zone.js/dist/zone-node';

import { ngExpressEngine } from '@nguniversal/express-engine';
import * as express from 'express';
import { join } from 'path';

const path = require('path');
const fs = require('fs');
const domino = require('domino');
const templateA = fs.readFileSync(path.join('dist/web/browser', 'index.html')).toString();
const win = domino.createWindow(templateA);
global['window'] = win;
global['document'] = win.document;
// Express server

import { AppServerModule } from './src/main.server';
import { APP_BASE_HREF } from '@angular/common';
import { existsSync } from 'fs';


// The Express app is exported so that it can be used by serverless Functions.
export function app(): express.Express {
  const server = express();
  const distFolder = join(process.cwd(), 'dist/web/browser');
  const indexHtml = existsSync(join(distFolder, 'index.original.html')) ? 'index.original.html' : 'index.html';



  // Our Universal express-engine (found @ https://github.com/angular/universal/tree/master/modules/express-engine)
  server.engine('html', ngExpressEngine({
    bootstrap: AppServerModule,
  }));

  server.set('view engine', 'html');
  server.set('views', distFolder);

  // Example Express Rest API endpoints
  // server.get('/api/**', (req, res) => { });
  // Serve static files from /browser
  server.get('*.*', express.static(distFolder, {
    maxAge: '1y'
  }));

  // All regular routes use the Universal engine
  server.get('*', (req, res) => {
    res.render(indexHtml, { req, providers: [{ provide: APP_BASE_HREF, useValue: req.baseUrl }] });
  });

  return server;
}

function run(): void {
  const port = process.env.PORT || 4000;

  // Start up the Node server
  const server = app();
  server.listen(port, () => {
    console.log(`Node Express server listening on http://localhost:${port}`);
  });
}

// Webpack will replace 'require' with '__webpack_require__'
// '__non_webpack_require__' is a proxy to Node 'require'
// The below code is to ensure that the server is run only when not requiring the bundle.
declare const __non_webpack_require__: NodeRequire;
const mainModule = __non_webpack_require__.main;
const moduleFilename = mainModule && mainModule.filename || '';
if (moduleFilename === __filename || moduleFilename.includes('iisnode')) {
  run();
}

export * from './src/main.server';

tsconfig.server.json

/* To learn more about this file see: https://angular.io/config/tsconfig. */
{
  "extends": "./tsconfig.app.json",
  "compilerOptions": {
    "outDir": "./out-tsc/server",
    "target": "es2016",
    "types": [
      "node"
    ],
    "module": "commonjs"
  },
  "files": [
    "src/main.server.ts",
    "server.ts"
  ],
  "angularCompilerOptions": {
    "entryModule": "./src/app/app.server.module#AppServerModule"
  }
}

我找到了解决方案。 我按照以下步骤意识到出了什么问题:

  1. 评论来自 app.module.ts 的所有导入和路由,我只是用一个简单的标签来标记 app.component.html 只是为了展示一些东西。在此步骤中,视图开始加载。
  2. 为每个模块添加模块并查看停止加载的位置。
  3. 我每行注释一行以查看错误的位置。

我发现的主要错误是 app.module.ts 和子模块上的路由导入顺序,

@NgModule({
        declarations: [
                AppComponent
        ],
        imports: [
                BrowserModule.withServerTransition({ appId: 'serverApp' }),
                FormsModule,
                ReactiveFormsModule,
                BrowserAnimationsModule,
                HttpClientModule,
                AppRoutingModule, // <-- here
        ],
        providers: [{ provide: HTTP_INTERCEPTORS, useClass: RequestInterceptorService, multi: true }],
        bootstrap: [AppComponent]
})
export class AppModule {}

另一个是在某些构造函数组件中我正在执行 api 调用但由于身份验证而失败。所以我需要添加一个验证,如果是平台浏览器则只执行它:

constructor(@Inject(PLATFORM_ID) private platformId: Object) {
    if (isPlatformBrowser(this.platformId)) {
     // api call
    }
  }

还好我的项目还不是很大