我有一个基于SSR的反应应用程序,目前正在实施Workbox工具,用于预先缓存和离线功能。我遇到的问题主要是因为该网站依赖服务器端的cookie并根据这些问题发布重定向。
初始加载工作正常,但是一旦服务工作者(sw)在线并且另一次刷新导致sw使用工作箱源中的URL进行获取调用。在此期间,服务器找不到cookie(fetch不带凭证 - link)并向不同的URL发出重定向(302)(这允许您将一些选项设置为cookie并刷新到旧URL )。
这会导致客户端The FetchEvent for "http://localhost:8080/" resulted in a network error response: a redirected response was used for a request whose redirect mode is not "follow".
服务器将重定向视为302状态,但客户端会导致:
site can’t be reached
The web page at http://localhost:8080/ might be temporarily down or it may have moved permanently to a new web address.
ERR_FAILED
这是我的服务工作者代码,资产由workbox-webpack插件填充。
/* global importScripts, WorkboxSW */
importScripts('/client/workbox-sw.prod.js')
// Create Workbox service worker instance
const workboxSW = new WorkboxSW({
clientsClaim: true,
cacheId: 'app-v3-sw',
})
// Placeholder array which is populated automatically by workboxBuild.injectManifest()
workboxSW.precache([])
// cache the offline html to be used as fallback navigation route.
workboxSW.router.registerRoute(
'/offline.html',
workboxSW.strategies.networkFirst({
networkTimeoutSeconds: 2,
cacheableResponse: { statuses: [0, 200] },
})
)
// cache google api requests.
workboxSW.router.registerRoute(
/\.googleapis\.com$/,
workboxSW.strategies.staleWhileRevalidate({
cacheName: 'v3-google-api-cache',
networkTimeoutSeconds: 2,
cacheableResponse: { statuses: [0, 200] },
})
)
// cache external requests.
workboxSW.router.registerRoute(
/(static\.clevertap\.com|www\.google-analytics\.com|wzrkt\.com|www\.googletagservices\.com|securepubads\.g\.doubleclick\.net|www\.googletagmanager\.com)/,
workboxSW.strategies.cacheFirst({
cacheName: 'v3-externals-cache',
cacheExpiration: {
maxEntries: 30,
},
cacheableResponse: { statuses: [0, 200] },
})
)
// Check if client can hit the url via network, if cannot then use the offline fallback html.
// https://github.com/GoogleChrome/workbox/issues/796
workboxSW.router.registerRoute(
({ event }) => event.request.mode === 'navigate',
({ url }) =>
// eslint-disable-next-line compat/compat
fetch(url.href).catch(() => caches.match('/offline.html'))
)
P.S。 这是我第一次尝试使用工作箱工具或服务工作者,我可能错过了或监督了一些细节。请指点我的方向。
答案 0 :(得分:0)
默认情况下,fetch
没有通过Cookie,因此您需要在选项中添加凭据:
workboxSW.router.registerRoute(
({ event }) => event.request.mode === 'navigate',
({ url }) => fetch(url.href, {credentials: 'same-origin'}).catch(() => caches.match('/offline.html'))
)