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

问题描述

我正在尝试将 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('*',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
    }
  }

幸运的是我的项目还不是很大。