Angular 6 Service Worker拒绝缓存资产,因为ngsw.json无法正确获取

时间:2018-07-12 19:06:22

标签: angular service-worker pwa angular-service-worker

当前行为

我做了ng add @angular/pwa,并且在生产版本中出现此错误

    Uncaught (in promise) SyntaxError: Unexpected token < in JSON at position 0
        at Driver.<anonymous> (ngsw-worker.js:2297)
        at Generator.next (<anonymous>)
        at fulfilled (ngsw-worker.js:1752)

screenshot from 2018-07-12 16-13-32 我做了一些研究,发现有问题 /ngsw.json?ngsw-cache-bust=0.08769372894975769 GET请求。尽管fetchLatestManifest返回200状态代码,但响应实际上不是JSON,而是其无脚本版本的index.html

您可以看到/ngsw.json?ngsw-cache-bust=0.08769372894975769的响应状态为200 screenshot from 2018-07-12 16-18-33

,但实际响应不是必需的JSON screenshot from 2018-07-12 16-19-14

我尝试在Chrome中将复制作为获取选项 实际 ```

fetch("https://officehawk.com/ngsw.json?ngsw-cache-bust=0.7927584506157848", {"credentials":"omit","headers":{},"referrer":"https://officehawk.com/ngsw-worker.js","referrerPolicy":"no-referrer-when-downgrade","body":null,"method":"GET","mode":"cors"});

``` 我从提取的网址部分删除了?ngsw-cache-bust=0.7927584506157848,我看到响应是JSON。

已编辑 ```

fetch("https://officehawk.com/ngsw.json", {"credentials":"omit","headers":{},"referrer":"https://officehawk.com/ngsw-worker.js","referrerPolicy":"no-referrer-when-downgrade","body":null,"method":"GET","mode":"cors"});

``` 所以你现在就可以看到ngsw.json的内容 screenshot from 2018-07-12 16-35-24

我怀疑必须在此功能中处理? https://github.com/angular/angular/blob/0b4d85e9f19246af68a75140afc4db3d97f9ddfd/packages/service-worker/worker/src/driver.ts#L645

环境

角度版本:6.0.0

浏览器: -[x] Chrome(台式机)67版

1 个答案:

答案 0 :(得分:3)

我最近在使用Nginx作为Web /反向代理服务器的Angular PWA上遇到此错误。

我解决了我在Nginx的虚拟服务器配置中遇到的问题。我从此更改了位置限制:

location / {
    root $root_path;
    index index.html;
    try_files $uri$args $uri$args/ index.html =404;

    error_page 404 =200 /index.html;
}

对此:

location / {
    root $root_path;
    index index.html;
    try_files $uri $uri$args $uri$args/ index.html =404;

    error_page 404 =200 /index.html;
}

区别在于try_files行。基本上,此行告诉Nginx如何检查所请求文件的路径。它们按从左到右的顺序进行评估。