如何使用工作箱服务工具工具允许cookie和处理302重定向?

问题描述 投票:2回答:1

我有一个基于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'))
)

附:这是我第一次尝试使用工作箱工具或服务工作者,我可能错过了或监督了一些细节。请指点我的方向。

service-worker workbox service-worker-events
1个回答
0
投票

默认情况下,fetch不会传递cookie,因此您需要在选项中添加凭据:

workboxSW.router.registerRoute(
  ({ event }) => event.request.mode === 'navigate',
  ({ url }) => fetch(url.href, {credentials: 'same-origin'}).catch(() => caches.match('/offline.html'))
)

更多信息:https://github.com/github/fetch#sending-cookies

© www.soinside.com 2019 - 2024. All rights reserved.