NUXT-PWA以缓存POST请求

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

我正在使用NUXT-PWA缓存我的数据,但是我有一个页面依赖于要构建的POST请求,并且我需要缓存JSON的响应,但是出现以下错误:

Uncaught (in promise) attempt-to-cache-non-get-request: Unable to cache '/api/hotel/order/get-voucher' because it is a 'POST' request and only 'GET' requests can be cached.

我在workbox-range-request.js中使用的代码是:

workbox.routing.registerRoute(
  new RegExp('/api/(.*)'),
  new workbox.strategies.CacheFirst({
    cacheName: 'apiCache',
    plugins: [
      new workbox.expiration.Plugin({
        maxEntries: 100,
        maxAgeSeconds: 7 * 24 * 60 * 60, // 7 Days
      }),
    ],
  }),
  'POST'
); 

和我的nuxt.config.js

  workbox: {
    dev:true,
    cachingExtensions: '@/plugins/workbox-range-request.js',
    runtimeCaching: [
      {
        urlPattern: 'https://www.google-analytics.com/.*',
        handler: 'StaleWhileRevalidate',
        method: 'GET',
        strategyOptions: { cacheableResponse: { statuses: [0, 200] } }
      }
    ]
  },

在文档中说它支持POST,但在控制台中出现错误,而在cacheStore中则没有数据。

progressive-web-apps nuxt workbox
1个回答
0
投票

缓存存储API阻止您在保存条目时将POST请求用作键。这部分是由于POST请求是“传统上”已发送到服务器以更改为远程状态的东西,而在该模型中,通过本地缓存的响应来实现这一点却从未到达服务器不会这样做。没道理。

但是,假设您发送POST请求后确实在响应主体中获取了有意义的数据,并且您想使用Cache Storage API通过GET请求来保存该响应主体,并可能不同的URL作为缓存键。

您可以通过cacheKeyWillBeUsed custom plugin使用Workbox进行此操作:

cacheKeyWillBeUsed

除非您有充分的理由明确地确定要在缓存中保存const savePostResponsePlugin = { cacheKeyWillBeUsed: async ({request, mode}) => { if (mode === 'write') { // Use the same URL as `POST` request as the cache key. // Alternatively, use a different URL. return request.url; } }, }; workbox.routing.registerRoute( new RegExp('/api/(.*)'), new workbox.strategies.CacheFirst({ cacheName: 'apiCache', plugins: [ // Add the custom plugin to your strategy. savePostResponsePlugin, new workbox.expiration.Plugin({...}), ], }), 'POST' ); 响应主体,否则我不建议您这样做。

[如果您只是由于脱机而在初次尝试失败时正在寻找重新发送POST请求的方法,我建议改为使用POST

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