0

我想看看我是否可以基于 CDN 和 Angular 2 Universal 创建一个堆栈。所以当用户导航时有CDN获取资产,如果用户第一次访问就会有Universal渲染的完整html。

我在想:

客户端 <===> Akamai <===> Varnish <===> 源服务器(具有通用的 node.js)

这听起来不错?你有没有尝试过?另外我正在考虑为整个堆栈添加 nginx 和 ELB。

问题是: - 这个堆栈可以按预期工作吗?

4

1 回答 1

0

是的,它可以做到!最大的问题是如何使在 Angular 中发出的任意数量的确定渲染页面的 http 请求无效。使用某种标头模式使无效可能会有所帮助。

假设您使用的是官方 ng-express 引擎,这样的服务可以让您定义来自 Angular 运行时的响应:

import { RESPONSE } from '@nguniversal/express-engine/tokens'
import { Inject, Injectable, Optional } from '@angular/core'
import { Response } from 'express'

export interface IServerResponseService {
  getHeader(key: string): string
  setHeader(key: string, value: string): this
  setHeaders(dictionary: { [key: string]: string }): this
  appendHeader(key: string, value: string, delimiter?: string): this
  setStatus(code: number, message?: string): this
  setNotFound(message?: string): this
  setError(message?: string): this
}

@Injectable()
export class ServerResponseService implements IServerResponseService {

  private response: Response

  constructor(@Optional() @Inject(RESPONSE) res: any) {
    this.response = res
  }

  getHeader(key: string): string {
    return this.response.getHeader(key)
  }

  setHeader(key: string, value: string): this {
    if (this.response)
      this.response.header(key, value)
    return this
  }

  appendHeader(key: string, value: string, delimiter = ','): this {
    if (this.response) {
      const current = this.getHeader(key)
      if (!current) return this.setHeader(key, value)

      const newValue = [...current.split(delimiter), value]
        .filter((el, i, a) => i === a.indexOf(el))
        .join(delimiter)

      this.response.header(key, newValue)
    }
    return this
  }

  setHeaders(dictionary: { [key: string]: string }): this {
    if (this.response)
      Object.keys(dictionary).forEach(key => this.setHeader(key, dictionary[key]))
    return this
  }

  setStatus(code: number, message?: string): this {
    if (this.response) {
      this.response.statusCode = code
      if (message)
        this.response.statusMessage = message
    }
    return this
  }

  setNotFound(message = 'not found'): this {
    if (this.response) {
      this.response.statusCode = 404
      this.response.statusMessage = message
    }
    return this
  }

  setError(message = 'internal server error'): this {
    if (this.response) {
      this.response.statusCode = 500
      this.response.statusMessage = message
    }
    return this
  }
}
于 2017-07-06T22:28:15.927 回答