angular - 上传 PUT 请求由 Angular ServiceWorker 发送两次

我们在 Angular 7 应用程序中使用 serviceWorker。 当用户通过 PUT 请求将文件(图像或 PDF)从应用程序上传到 AWS S3 时,会触发 2 个 PUT 请求,而不是 1 个。第一个 PUT 请求来自 ServiceWorker,虽然它不应该,但上传是从主线程完成的。第二个不是来自 ServiceWorker,似乎没有文件发送。

因此,文件被错误地上传为 0 字节大小到 S3。仅当我们在启用 ServiceWorker 的情况下运行应用程序时才会发生此问题。 似乎 ServiceWorker 正在缓存上传请求。

如何避免这种情况?

这是我在开发工具的网络选项卡中看到的:https://prnt.sc/odoaac

这里是angular.json配置:

"production": {
    "fileReplacements": [
      {
        "replace":"apps/echo/src/environments/environment.ts",
        "with":"apps/echo/src/environments/environment.prod.ts"
      }
    ],
  "serviceWorker": true,
  "ngswConfigPath": "apps/echo/src/ngsw-config.json",
  "optimization": true,
  "outputHashing": "all",
  "sourceMap": false,
  "extractCss": true,
  "namedChunks": false,
  "aot": true,
  "extractLicenses": true,
  "vendorChunk": false,
  "buildOptimizer": true,
  "budgets": [
    {
      "type": "initial",
      "maximumWarning": "2mb",
      "maximumError": "5mb"
    }
  ]
}

这里是 ngsw-config.json 数据组:

"dataGroups": [
  {
    "cacheConfig": {
      "maxSize": "1",
      "maxAge": "0u",
      "timeout": "10m",
      "strategy": "freshness"
    },
    "name": "API",
    "urls": [
      "https://api.editorial.reali.com",
      "https://api.editorial.reali.com/",
      "https://api.editorial.reali.com/*",
      "https://api.editorial.reali.com/**",
      "https://s3.amazonaws.com",
      "https://s3.amazonaws.com/",
      "https://s3.amazonaws.com/*",
      "https://s3.amazonaws.com/**",
      "/version.json"
    ]
  },
  {
    "name": "GoogleFonts",
    "cacheConfig": {
      "maxSize": "20",
      "maxAge": "5d",
      "timeout": "1s",
      "strategy": "performance"
    },
    "urls": [
      "https://fonts.googleapis.com/**"
    ]
  }
]

最佳答案

实际上只有一个 PUT 请求到服务器。您应该能够从您的 S3 访问日志中确认这一点。

devtools 截图中发生了什么(我在这里重新添加它以供将来引用!)是这样的:

  1. 页面JS发送PUT请求被SW拦截
  2. SW 在拦截请求后,决定向服务器发出实际请求
  3. 当发出实际请求时,浏览器发现目标域不同
  4. 由于域不同,浏览器自动向服务器发送CORS预检请求(https://developer.mozilla.org/en-US/docs/Glossary/Preflight_request)并确认服务器支持PUT
  5. 服务器响应预检请求并表示 PUT 正常
  6. 浏览器向服务器发送真实的、最终的、唯一的 PUT 请求

由于某种原因,您的文件在这里的某个地方被删除了。我不确定为什么,因为我没有处理 Service Workers 中的文件上传。

https://stackoverflow.com/questions/56991902/

相关文章:

node.js - 事件.js :180 throw er;//Unhandled 'error'

angular - Ionic 4 - 在平台硬件后退按钮 android 上关闭或关闭模态

react-native - 位于 "node_modules/web3-eth-accounts/

java - 在非 View 或非 ViewModel 类中观察 LiveData

python - 为什么 GridSearchCV 方法的精度低于标准方法?

angular - 自动滚动 onkeydown 即使没有必要

django - 如何解决“"django.core.exceptions.AppRegistryN

laravel - 安装后如何使用 npm 包 (chart.js)?

amazon-web-services - 为什么 Amazon Athena 会抛出 "Acces

assembly - 如何在 GDB 控制台中设置 "info registers"中的变量 rip