繁体   English   中英

NUXT-PWA 缓存 POST 请求

[英]NUXT-PWA to cache the POST request

我正在使用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中我没有得到任何数据。

缓存存储 API 可防止您在保存条目时使用POST请求作为键。 这部分是因为POST请求“传统上”是实际发送到服务器以对远程 state 进行更改的东西,并且在那个 model 中,通过本地缓存的响应来实现这一点,而不会到达服务器感觉。

但是...假设您在发送POST请求后确实在响应正文中获得了有意义的数据,并且您希望使用缓存存储 API 保存该响应正文,使用具有可能不同的 URL 作为缓存键的GET请求.

您可以通过cacheKeyWillBeUsed自定义插件使用 Workbox 来做到这一点:

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请求的方法,我建议您改用workbox-background-sync

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM