我有一個簡單的角度應用程序與服務器端渲染。我描述了我的組件的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);
});
}
}
是的,但有可能避免第一GET請求?正確地請求服務器,因爲對於我來說,請求帶有某些標頭(如cookie)很重要,例如?這意味着來自服務器端的請求是無用的。 –
是的,你可以通過調整代碼避免,我會更新我的答案。 –