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

标签 node.js angular express server-side-rendering

我正在尝试将 SSR 添加到我的网站,但内容未加载。我正在使用 Angular Universal,我遵循了这个 guide用于初始配置。 http://localhost:4200/ 它没有完成加载,也没有显示错误。 http://localhost:4200/index.html 返回一个空 View 。

构建过程成功。

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 中留下一个简单的标记,只是为了显示一些内容。在此步骤中, View 开始加载。
  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
    }
  }

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

关于node.js - Angular 通用服务器端渲染 (SSR) res.render 未加载,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66632403/

相关文章:

javascript - Angular2中组件属性变化的Observable

angular - 包含一个具有依赖项的模块作为 Webpack 中的入口点(Angular 2 Typescript)

javascript - 保存到主干模型和表达后如何重定向 url

angular - ngrx 成功操作后如何清理我的表单?

node.js - Parse Cloud code "first"查询数组返回不同的结果

javascript - 使用我的浏览器访问本地主机页面但服务器正在运行时出现错误 "str.substr is not a function"?

javascript - nodejs 中的 Promises 和 async/await

javascript - Node.JS/Express Views 中页眉/页脚/可重用模板的最佳实践?

css - 在表单提交上显示元素

javascript - Node js - 加载循环