首页 > 解决方案 > 从网络服务器调用时,Angular 没有缓存 localhost api url

问题描述

目标:缓存来自http://localhost/api的特定 url

实际结果:根本没有缓存。

预期结果:将带有图像的响应缓存为 url 的 blob。

详细描述:Angular App 运行在带有 https 证书的网络服务器上。API 在本地启动,并在地址http://localhost:80/api下运行。每个电话都工作正常并且正在响应。

如果我在 localhost 上同时运行 Angular 应用程序和 API,缓存工作正常。所以我认为这是一个跨源问题,或者服务人员忽略了 localhost url。

ngsw.json

{
  "index": "/index.html",
  "assetGroups": [
    {
      "name": "app",
      "installMode": "prefetch",
      "resources": {
        "files": [
          "/favicon.ico",
          "/index.html",
          "/*.css",
          "/*.js"
        ]
      }
    },
    {
      "name": "assets",
      "installMode": "lazy",
      "updateMode": "prefetch",
      "resources": {
        "files": [
          "/assets/**",
          "/*.(eot|svg|cur|jpg|png|webp|gif|otf|ttf|woff|woff2|ani)"
        ],
        "urls": [
          "https://fonts.googleapis.com/**",
          "http://localhost/api/article/**",
          "http://localhost/api/detail/**",
          "http://localhost/api/item/preview?id=**"
        ]
      }
    }
  ],
  "dataGroups": [
    {
      "name": "api-performance",
      "urls": [
        "article/**",
        "detail/**",
        "item/preview?id=*"
      ],
      "cacheConfig": {
        "strategy": "performance",
        "maxSize": 100,
        "maxAge": "3d"
      }
    }
  ]
}

在最后一个正斜杠之后,我要缓存的 url 非常动态:

"http://localhost/api/article/${articleId}",
"http://localhost/api/detail/${detailId}",
"http://localhost/api/item/preview?id=${previewId}"

所有响应都是字节流(blob),我将其转换为 SafeUrls。

已经尝试过:

无法提供网络服务器和 api 的最小示例。

标签: angular

解决方案


做了一些测试:问题是由本地主机地址引起的。我尝试了几个来自“互联网”的 API,它们有一个带通配符的真实 IP 地址/URL,而没有通配符。

此外,允许和使用自本地托管 API 可能是一个安全问题。


推荐阅读