【问题标题】:Angular 4 - Server side renderingAngular 4 - 服务器端渲染
【发布时间】:2018-03-21 13:10:33
【问题描述】:

我有一个带有服务器端渲染的简单 Angular 应用程序。我描述了我的组件的 ngOnInit,我在其中调用了 http.get 方法。但是如果我在我的 Rest 端点上设置调试,我会看到这个方法调用了两次。除了第一次调用我得到 HttpRequest 没有凭据,第二个 - 有凭据。为什么?在控制台上通过 console.log 我只看到一个电话。我怎样才能实现只调用一次并使用凭据?

app.module.ts

    import { BrowserModule } from '@angular/platform-browser';
    import { NgModule } from '@angular/core';

    import { AppComponent } from './app.component';
    import {HttpModule} from "@angular/http";
    import {FormsModule} from "@angular/forms";
    import {HttpClientModule} from "@angular/common/http";

    @NgModule({
      declarations: [
        AppComponent
      ],
      imports: [
        BrowserModule.withServerTransition({appId: 'angular-universal'}),
        FormsModule,
        HttpClientModule,
        HttpModule
      ],
      providers: [],
      bootstrap: [AppComponent]
    })
    export class AppModule { }

app.server.module.ts

 import { NgModule } from '@angular/core';
    import { ServerModule } from '@angular/platform-server';
    import { AppModule } from './app.module';
    import { AppComponent } from './app.component';

    @NgModule({
      imports: [
        ServerModule,
        AppModule
      ],
      bootstrap: [AppComponent]
    })
    export class AppServerModule { }

server.ts

    import 'reflect-metadata';
    import 'zone.js/dist/zone-node';
    import { platformServer, renderModuleFactory } from '@angular/platform-server'
    import { enableProdMode } from '@angular/core'
    import { AppServerModuleNgFactory } from '../dist/ngfactory/src/app/app.server.module.ngfactory'
    import * as express from 'express';
    import { readFileSync } from 'fs';
    import { join } from 'path';

    const PORT = 4000;

    enableProdMode();

    const app = express();

    let template = readFileSync(join(__dirname, '..', 'dist', 'index.html')).toString();

    app.engine('html', (_, options, callback) => {
      const opts = { document: template, url: options.req.url };

      renderModuleFactory(AppServerModuleNgFactory, opts)
        .then(html => callback(null, html));
    });

    app.set('view engine', 'html');
    app.set('views', 'src')

    app.get('*.*', express.static(join(__dirname, '..', 'dist')));

    app.get('*', (req, res) => {
      res.render('index', { req,  preboot: true});
    });

    app.listen(PORT, () => {
      console.log(`listening on http://localhost:${PORT}!`);
    });

app.coponent.ts

    import { Component, OnInit, Inject, PLATFORM_ID } from '@angular/core';
    import {Hero} from "./hero";
    import {HttpClient} from "@angular/common/http";
    import 'rxjs/add/operator/map';

    @Component({
      selector: 'app-root',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.scss']
    })
    export class AppComponent implements OnInit{
      title = 'app';
      hero: Hero;
      constructor(private http: HttpClient){
      }

      ngOnInit(): void {
        this.http.get('http://localhost:8080/test', { withCredentials: true }).subscribe(data => {
          console.log("Init component");
          console.log(data);
        });
      }

    }

【问题讨论】:

    标签: angular angular-universal


    【解决方案1】:

    如果您使用 Angular Universal 进行服务器端渲染,那么它将首先在服务器端渲染页面(第一次 GET 请求),然后在浏览器中再次渲染(第二次 GET 请求)。

    有一种称为状态传输的技术,它允许您“缓存”服务器发出的请求,将它们传输到您的客户端并重复使用响应,因此您无需再次发出它们。此功能目前正在实现为 angular/universal,但您自己实现它相当容易(使用 HttpClient 拦截器)。

    您还可以在代码中添加条件,例如您不会从您知道它们会失败的服务器端发出 API 请求(例如,缺少授权)。

    你可以这样做:

    constructor(@Inject(PLATFORM_ID) private platformId: Object) { ... }
    
    ngOnInit() {
        if (isPlatformBrowser(this.platformId)) {
            // Client only code.
        ...
        }
        if (isPlatformServer(this.platformId)) {
            // Server only code.
        ...
        }
    }
    

    【讨论】:

    • 是的,但是是否可以避免第一次 GET 请求?正是来自服务器的请求,因为对我来说,请求带有某些标头很重要,例如 cookie?这意味着来自服务器端的请求是无用的。
    • 是的,你可以通过调整代码来避免,我会更新我的答案。
    【解决方案2】:

    由于您的 API 在不同的服务器 localhost:8000 上运行,我很确定使用了 CORS(跨源资源共享)协议。

    如果 POST 或 GET 中包含任何非简单内容或标头,CORS 规范要求 OPTIONS 调用位于 POST 或 GET 之前。它也称为preflight request,更多信息请参见this link

    因此,如果您查看标题,您很可能会看到,第一个调用是 OPTIONS 调用,第二个调用是实际的 GET。

    对于您的问题:此行为是设计使然,如果您跨不同来源发出请求,则这是必要的。

    【讨论】:

      【解决方案3】:

      角度服务器端渲染一步一步在评论下方运行

      第一步:->ng add @ng-toolkit/universal

      第二步:->npm install

      第三步:->npm run build:prod

      第四步:->ng build --prod

      第五步:->npm run server

      第6步:->运行cmd并编写命令->curl http://localhost:4000

      我的服务器端 Angular 应用程序 https://exampreparation.study

      【讨论】:

        猜你喜欢
        • 2019-09-07
        • 1970-01-01
        • 2018-12-13
        • 1970-01-01
        • 2017-04-27
        • 2020-01-24
        • 2019-05-30
        • 1970-01-01
        • 2021-10-20
        相关资源
        最近更新 更多