Ara*_*han 1 service-worker angular angular-service-worker pwa
我做了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)
Run Code Online (Sandbox Code Playgroud)
我做了一些研究,发现/ngsw.json?ngsw-cache-bust=0.08769372894975769GET 请求存在问题
。尽管 fetchLatestManifest 返回 200 状态代码,响应实际上不是 JSON ,而是它的无脚本版本index.html
您可以看到响应状态为 200 /ngsw.json?ngsw-cache-bust=0.08769372894975769

但实际响应不是所需的 JSON

我尝试复制作为 chrome 中的 fetch 选项实际 ```
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"});
Run Code Online (Sandbox Code Playgroud)
``` 并且我?ngsw-cache-bust=0.7927584506157848从 fetch 的 URL 部分中删除,我可以看到响应是 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"});
Run Code Online (Sandbox Code Playgroud)
``` 这样你就可以看到 ngsw.json 的内容了

我怀疑它必须在这个函数中处理? https://github.com/angular/angular/blob/0b4d85e9f19246af68a75140afc4db3d97f9ddfd/packages/service-worker/worker/src/driver.ts#L645
角度版本:6.0.0
浏览器: - [x] Chrome(桌面)版本 67
小智 5
我最近在使用 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;
}
Run Code Online (Sandbox Code Playgroud)
对此:
location / {
root $root_path;
index index.html;
try_files $uri $uri$args $uri$args/ index.html =404;
error_page 404 =200 /index.html;
}
Run Code Online (Sandbox Code Playgroud)
区别在于 try_files 行。基本上这一行告诉 Nginx 如何检查被请求文件的路径。它们按从左到右的顺序进行评估。