我有一个部署到 Azure 的 Node 应用程序,其中一个测试分支指向暂存实例,一个主分支指向生产部署。我的应用程序在本地应用程序的所有实例上运行良好,但生产和暂存存在一个问题,如果它们已经缓存,则它们将无法加载,并且在刷新后将显示为空白,最后将在缓存重置时正常工作。
每当我刷新生产中的页面时,它都是空白的。服务工作人员正在运行(我可以在 chrome serviceworkers-internal 工具中看到它),但页面从未加载。生成的文件引用是正确的。您可以在此处查看正在发生的情况的示例:Live Site然后您还可以看到测试站点也因部署完全相同的代码而失败:Test Site .
整个 ServiceWorker 实现都是从 create-react-app
中开箱即用的。我花了几个小时试图在react-boilerplate 和 create-react-app 存储库下的各种 GitHub 问题中追踪这个错误,但除了限制页面缓存之外,没有一个真正能达到任何目的,我尝试这样做但没有成功与:
索引.html
<meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate"/>
<meta http-equiv="Pragma" content="no-cache"/>
<meta http-equiv="Expires" content="0"/>
您可以在the repo that hosts all of this code.找到您对任何代码有疑问的任何代码。
我刚刚接触 React/Node,所以我陷入了困境,不知道如何在不完全取消 ServiceWorker 注册的情况下解决这个问题。
编辑:我从 index.js
文件中完全删除了 ServiceWorker 代码,并且 View 现在重新加载,没有任何问题。我需要完成一个步骤才能让 ServiceWorker 正确地从缓存或其他内容中重新加载页面吗?
最佳答案
如果其他人像我一样发现这个问题,答案是禁用 Service Worker 文件(对我来说是 service-worker.js)和 index.html 上的浏览器缓存,并永久缓存其余部分。
当进行更改时,旧版本的应用程序会继续运行,并且在启动时会检测到有新版本。如果像我一样,您不缓存静态资源,那么当它尝试获取旧版本时,它会收到 404 错误,导致空白页面。如果您第二次刷新,它将获取应用程序的新版本。
我通过修改 registerServiceWorker.js 添加了一些代码,以便在 5 秒后自动重新加载。
function registerValidSW(swUrl) {
console.debug('Registering serviceWorker URL [' + swUrl + ']');
navigator.serviceWorker
.register(swUrl)
.then(registration => {
registration.onupdatefound = () => {
const installingWorker = registration.installing;
installingWorker.onstatechange = () => {
if (installingWorker.state === 'installed') {
if (navigator.serviceWorker.controller) {
// At this point, the old content will have been purged and
// the fresh content will have been added to the cache.
// It's the perfect time to display a "New content is
// available; please refresh." message in your web app.
reportInfo('App has been updated. This page will refresh in 5 seconds.');
setInterval(()=>window.location.reload(), 5000);
} else {
// At this point, everything has been precached.
// It's the perfect time to display a
// "Content is cached for offline use." message.
reportInfo('App is cached for offline use.');
}
}
};
};
})
.catch(error => {
reportError('Error during service worker registration:', error);
});
}
关于node.js - Service Worker 在 React 应用程序中刷新后导致空白页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46500869/