错误消息:
NullInjectorError: R3InjectorError(AppServerModule)
WindowRef -> InjectionToken SERVER_REQUEST_URL -> InjectionToken SERVER_REQUEST_URL -> InjectionToken SERVER_REQUEST_URL -> InjectionToken REQUEST]:
NullInjectorError: No provider for InjectionToken REQUEST!
Angular universal engine 的文档:
https://github.com/angular/universal/tree/master/modules/express-engine
服务器端的 HTTP request 调用,通过
Injection token
注入到 SSR Application 里:
import { Request } from 'express';
import { REQUEST } from '@nguniversal/express-engine/tokens';
@Injectable()
export class RequestService {
constructor(@Inject(REQUEST) private request: Request) {}
这个 token 在客户端环境下不可用。
相关错误:https://github.com/angular/universal-starter/issues/423
https://gitter.im/angular/universal/archives/2018/06/17
REQUEST and RESPONSE won't exist when you run in the browser context, even when you are running the SSR server
Use @Optional and take care to check whether you've got it, and consider using isServerPlatform to detect when you are running on the server side
在浏览器上下文环境运行时,REQUEST 和 RESPONSE 不可用。使用 @Optional
来避免 NullInjectorError 错误,以及使用 isServerPlatform
检测当前的运行环境。
相关 issue:https://github.com/SAP/spartacus/issues/11016
The SERVER_REQUEST_ORIGIN and SERVER_REQUEST_URL should not be provided in CSR by design.
SERVER_REQUEST_ORIGIN
在文件 ssr-providers.ts
里提供实现: