1

以下配置会引发“不支持请求方法 'POST'”的错误。我已经读到存储 api 不使用 POST 方法请求对象作为缓存中的键,但我不知道如何添加路由,该路由显示了这些请求的 networkOnly 策略。

规格(设置取自https://github.com/nystudio107/annotated-webpack-4-config

  • 使用 GenerateSW

webpack.settings.js(记住 importScripts 语句)

workboxConfig: {
    swDest: "../sw.js",
    precacheManifestFilename: "js/precache-manifest.[manifestHash].js",
    importScripts: [
        "/dist/workbox-catch-handler.js"
    ],
    exclude: [
        /\.(png|jpe?g|gif|svg|webp)$/i,
        /\.map$/,
        /^manifest.*\\.js(?:on)?$/,
    ],
    globDirectory: "./web/",
    globPatterns: [
        "offline.html",
        "offline.svg"
    ],
    offlineGoogleAnalytics: true,
    runtimeCaching: [
        {
            urlPattern: /\.(?:png|jpg|jpeg|svg|webp)$/,
            handler: "cacheFirst",
            options: {
                cacheName: "images",
                expiration: {
                    maxEntries: 20
                }
            }
        }
    ]
}

wepack.prod.js

// webpack.prod.js - production builds
    const LEGACY_CONFIG = 'legacy';
    const MODERN_CONFIG = 'modern';
    const WorkboxPlugin = require('workbox-webpack-plugin');

// config files
    const settings = require('./webpack.settings.js');
    const common = require('./webpack.common.js');
    ...

// Configure Workbox service worker
      const configureWorkbox = () => {
         let config = settings.workboxConfig;

         return config;
      };

// Module Exports – simplified for clarity - see github repro for more details
   module.exports = [
      ...
      ...,
    merge(
       common.modernConfig,
       {
          ...
          ...
          plugins: [
             ...
             new WorkboxPlugin.GenerateSW(
                configureWorkbox()
             ),
          ]
       }
   ]

工作箱-catch-handler.js

// fallback URLs
   const FALLBACK_HTML_URL = '/offline.html';
   const FALLBACK_IMAGE_URL = '/offline.svg';

// This "catch" handler is triggered when any of the other routes fail to
// generate a response.

   workbox.routing.setCatchHandler(({event, request, url}) => {
      // Use event, request, and url to figure out how to respond.
      // One approach would be to use request.destination, see
      // https://medium.com/dev-channel/service-worker-caching-strategies-based-on-request-types-57411dd7652c

         switch (request.destination) {
            case 'document':
               return caches.match(FALLBACK_HTML_URL);
               break;

            case 'image':
               return caches.match(FALLBACK_IMAGE_URL);
               break;

            default:
               // If we don't have a fallback, just return an error response.
               return Response.error();
         }
   });

// Use a stale-while-revalidate strategy for all other requests.
      workbox.routing.setDefaultHandler(
         workbox.strategies.staleWhileRevalidate()
      );

该错误是由 DefaultHandler 的策略引起的,因此我尝试在 DefaultHandler 正下方为这些请求添加另一条路由,但没有成功。例如:

workbox.routing.registerRoute(
   new RegExp('*/admin/*'),
   workbox.strategies.networkOnly()
);

我也尝试了 bgSyncPlugin,但没有成功。任何帮助表示赞赏。我想为 POST 请求(不仅仅是管理 URL)实施一个侧宽 networkOnly 策略。

4

1 回答 1

1

您不能使用 Cache API 缓存 POST 请求,这意味着您不能使用网络优先策略。

请参阅:服务人员可以缓存 POST 请求吗?

您可能能够对网络请求执行某些操作(即通过读取 POST 响应并生成新响应以放入 Cache API 来更改服务工作者中的请求类型)。这将需要自定义策略。

要使用 Workbox 路由器访问 POST 请求,请参阅:https ://developers.google.com/web/tools/workbox/modules/workbox-routing#defining_a_route_for_non-get_requests

要编写自己的函数来处理网络请求,请参阅:https ://developers.google.com/web/tools/workbox/modules/workbox-routing#matching_and_handling_in_routes

您也许可以重复使用一些工作箱策略,请在此处查看详细信息,了解其工作原理:https ://developers.google.com/web/tools/workbox/guides/advanced-recipes#make-requests

于 2018-12-05T21:48:28.353 回答