简体   繁体   中英

Angular 6 Service worker refuses to cache assets as the ngsw.json is not fetched correctly

Current behavior

i did ng add @angular/pwa and i have this error in production build

    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)

2018-07-12 16-13-32的屏幕截图 i did some research and found that there is issue with /ngsw.json?ngsw-cache-bust=0.08769372894975769 GET request. though the fetchLatestManifest returns 200 status code,response is not actually JSON , instead its no script version of index.html

you can see response status is 200 for /ngsw.json?ngsw-cache-bust=0.08769372894975769 2018-07-12 16-18-33的屏幕截图

but the actual response is not the required JSON 2018-07-12 16-19-14的屏幕截图

i tried copy as fetch option in chrome Actual ```

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"});

``` and i removed ?ngsw-cache-bust=0.7927584506157848 from the URL part of fetch and i can see that the response is JSON.

Edited ```

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"});

``` so you can see the contents of ngsw.json now 2018-07-12 16-35-24的屏幕截图

i suspect it has to be handled in this function ? https://github.com/angular/angular/blob/0b4d85e9f19246af68a75140afc4db3d97f9ddfd/packages/service-worker/worker/src/driver.ts#L645

Environment

Angular version: 6.0.0

Browser: - [x ] Chrome (desktop) version 67

I recently encountered this error on my Angular PWA using Nginx as my web/reverse proxy server.

I resolved my issue in my virtual server configuration for Nginx. I changed my location block from this:

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

    error_page 404 =200 /index.html;
}

To this:

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

    error_page 404 =200 /index.html;
}

The difference is on the try_files line. Basically this line tells Nginx how to check the path of the files being requested. They are evaluated in left to right order.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM