【问题标题】:NUXT-PWA to cache the POST requestNUXT-PWA 缓存 POST 请求
【发布时间】:2019-11-02 10:17:33
【问题描述】:

我正在使用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.js workbox


    【解决方案1】:

    缓存存储 API 可防止您在保存条目时使用 POST 请求作为键。这部分是因为POST 请求“传统上”是实际发送到服务器以更改远程状态的东西,并且在该模型中,通过本地缓存响应来实现这一点,而不会到达服务器。没有意义。

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

    您可以通过 cacheKeyWillBeUsed custom plugin 使用 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

    【讨论】:

      猜你喜欢
      • 2021-01-15
      • 2019-11-01
      • 2014-11-25
      • 2012-02-19
      • 2016-12-26
      • 2014-06-17
      • 1970-01-01
      • 2015-12-20
      • 1970-01-01
      相关资源
      最近更新 更多