两种办法,应用 config.backend.timeout = { 浏览器:...,服务器:...} ,或者能够更具体地配置,即基于 Request 粒度,通过将 HTTP_TIMEOUT_CONFIG HttpContextToken 传递给 Angular HttpClient 的办法来针对每个具体申请进行配置。

在SSR(Node.js)中,超时解决耗时过长的内部http调用是一项尤为重要的改良,因为在Node.js中,与浏览器不同,Node.js 运行环境下并没有默认的内部http调用超时工夫(浏览器通常会在长时间后超时长时间的http调用,例如1分钟)。

这种可配置的超时逻辑当初曾经在Spartacus中的 Angular Http拦截器层面上实现。也就是说,在 Spartacus SSR long API timeout 性能公布之前,客户能够本人实现相似的逻辑,例如通过本人实现 Angular Http 拦截器来实现。

配置代码:

provideConfig({   backend: {     timeout: {       server: 3_000,      browser: 3_000    }  }})

如何应用代理服务器制作后盾 API 响应的延时成果

首先Install http-proxy tool:npm install -g http-proxy

而后开发一个 http-proxy.js server file

const httpProxy = require('http-proxy');const http = require('http');const proxy = httpProxy.createProxyServer({ secure: false });const ENDPOINT_FOR_DELAY = 'consenttemplates';const BACKEND_BASE_URL = 'https://jerry:9002';const DELAY = 3000; // 手动硬编码的延时/** custom predicate, whether we should delay a request */const shouldDelay = (req) => {  // Note: In browser there are 2 requests: preflight (OPTIONS) and actual request (GET).  const result = req.url.includes(ENDPOINT_FOR_DELAY);  result && console.log({ delay: DELAY, url: req.url, method: req.method });  return result;};http  .createServer(function (req, res) {    const forwardRequest = () =>      proxy.web(req, res, { target: BACKEND_BASE_URL });    const delay = shouldDelay(req) ? DELAY : 0;    setTimeout(forwardRequest, delay);  })  .listen(9002);

而后启动这个代理服务器:node http-proxy.js

最初在 .env-cmdrc 里指定环境变量 CX_BASE_URL:

  "dev": {    "CX_BASE_URL": "http://localhost:9002"  },

针对某个具体申请设置 timeout:

import { HTTP_TIMEOUT_CONFIG, HttpTimeoutConfig } from `@spartacus/core`;/* ... */return this.httpClient.get('/some/api', {  context: new HttpContext().set(    HTTP_TIMEOUT_CONFIG,     { server: 15_000 } // value in milliseconds   )})

当超时真的产生之后,能够在 console 看到下列的正告音讯:

Request to URL '${request.url}' exceeded expected time of ${timeoutValue}ms and was aborted.

总之,对于在 NodeJS 中运行的服务器端渲染应用程序的稳定性来说,为每个传出的 http 调用设置一个明确的超时工夫是至关重要的。 否则,如果后端 API 响应十分慢(或从不响应),服务器端出现的应用程序将期待响应很长时间(或永远)。 在这种状况下,为该应用程序调配的内存不会被开释,这会引起内存透露问题。