Angular 4 - 服务器端渲染

Angular 4 - 服务器端渲染

问题描述:

我有一个简单的角度应用程序与服务器端渲染。我描述了我的组件的ngOnInit,我在那里调用http.get方法。但是如果我在Rest端点上设置调试,我发现这个方法调用了两次。除了第一次打电话时,我会得到没有凭证的HttpRequest,第二次 - 凭证。为什么?并通过console.log在控制台上,我只看到一个调用。我如何才能使用凭证只调用一次该休息?Angular 4 - 服务器端渲染

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); 
     }); 
     } 

    } 

如果您使用角度通用进行服务器端呈现,那么它将首先在服务器端呈现页面(第1个GET请求),然后再次在浏览器中呈现(第2个GET请求)。

有一种称为状态转移的技术,它允许您“缓存”由服务器发出的请求,将它们转移到您的客户端并重新使用响应,因此您不需要再次创建它们。此功能目前正在实现角度/通用,但它很容易由您自己实现(使用HttpClient拦截器)。

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

这是你如何做到这一点:

constructor(@Inject(PLATFORM_ID) private platformId: Object) { ... } 

ngOnInit() { 
    if (isPlatformBrowser(this.platformId)) { 
     // Client only code. 
    ... 
    } 
    if (isPlatformServer(this.platformId)) { 
     // Server only code. 
    ... 
    } 
} 
+0

是的,但有可能避免第一GET请求?正确地请求服务器,因为对于我来说,请求带有某些标头(如cookie)很重要,例如?这意味着来自服务器端的请求是无用的。 –

+0

是的,你可以通过调整代码避免,我会更新我的答案。 –

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

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

所以如果你看看头文件,你很可能会看到,第一个调用是OPTIONS调用,第二个调用是实际的GET。

对于你的问题:这种行为是有意设计的,如果你在不同来源提出请求,这种行为是必须的。