我有一个带有 Service Worker 的 Angular 16 网页。该页面由我控制下的 NGINX 提供服务。 最近我注意到,当访问该页面时,浏览器显示的是旧版本。我必须刷新网页才能获取当前版本。 一段时间后重新打开页面时,旧页面再次显示。
我尝试禁用 NGINX 上的缓存,但这不起作用。
location / {
root /usr/share/nginx/html;
index index.html index.htm;
try_files $uri$args $uri$args/ /index.html;
expires off;
add_header Cache-Control "no-cache, no-store, must revalidate";
}
我还尝试编写一个 UpdateService 以在更新可用时重新加载页面。但我想已经太晚了。
@Injectable({
providedIn: 'root',
})
export class UpdateAppService {
constructor(swUpdate: SwUpdate) {
swUpdate.versionUpdates
.pipe(
tap(console.log),
filter((evt): evt is VersionReadyEvent => evt.type === 'VERSION_READY')
)
.subscribe((evt) => {
document.location.reload();
});
}
}
这是我的
ngsw-config.json
{
"$schema": "../../node_modules/@angular/service-worker/config/schema.json",
"index": "/index.html",
"assetGroups": [
{
"name": "app",
"installMode": "prefetch",
"resources": {
"files": [
"/favicon.ico",
"/index.html",
"/manifest.webmanifest",
"/*.css",
"/*.js"
]
}
},
{
"name": "assets",
"installMode": "lazy",
"updateMode": "prefetch",
"resources": {
"files": [
"/assets/**",
"/*.(svg|cur|jpg|jpeg|png|apng|webp|avif|gif|otf|ttf|woff|woff2)"
]
}
}
]
}
我没有元标记来防止在
index.html
本身上进行缓存。
网址
/ngsw/state
似乎显示错误。
NGSW Debug Info:
Driver version: 16.1.8
Driver state: SAFE_MODE (Initialization failed due to error: Unexpected token '<', "<!DOCTYPE "... is not valid JSON
SyntaxError: Unexpected token '<', "<!DOCTYPE "... is not valid JSON)
Latest manifest hash: none
Last update check: 12s307u
=== Idle Task Queue ===
Last update tick: 12s30u
Last update run: 7s22u
Task queue:
Debug log:
NGINX 配置似乎是导致 Service Worker 加载错误文件的原因。服务人员然后切换到
SAFE_MODE
。
我已使用以下代码交换了配置,现在它可以工作了。
server {
listen 80;
listen [::]:80;
server_name localhost;
#access_log /var/log/nginx/host.access.log main;
root /usr/share/nginx/html;
index index.html;
location / {
try_files $uri $uri/ /index.html;
}