Workbox 后台同步无法匹配 Regex

Workbox background sync cant match Regex

使用工作箱后台同步插件时,我必须创建一个路由来捕获请求。但我想捕获所有包含 /api/

的 url

来自 Documentation 这是默认的正则表达式 //api/./.json/

registerRoute(
  /\/api\/.*\/*.json/,
  new NetworkOnly({
    plugins: [bgSyncPlugin]
  }),
  'POST'
);

正则表达式将匹配 https://example.com /api/test.json

我正在尝试这样做以匹配 url 中具有 /api/ 的所有 url 例如:

https://example.com/api/user/add/https://somethingelse.com/api/todo/add/

但出于某种原因,当我这样做时:

registerRoute(
  new RegExp(/.*\/api\/.*/),
  new NetworkOnly({
    plugins: [bgSyncPlugin]
  }),
  'POST'
);

后台同步插件没有捕捉到 post 请求。我不明白为什么它不起作用,正则表达式在 regex101

中测试时确实匹配

为什么 workbox 后台同步插件在 https://example.com/api/users/

上无法与 new RegExp('.*\/api\/.*/') 一起使用

我也确认是这个问题。当专门匹配我的域 url 时它有效。

Workbox documentation:

中有一些关于此的背景信息

Just like with string matching, requests for different origins are treated differently. Instead of matching against any part of the URL, the regular expression must match from the beginning of the URL in order to trigger a route when there's a cross-origin request.

For example, the previous regular expression new RegExp('/blog/\d{4}/\d{2}/.+') would not match a request for https://some-other-origin.com/blog/<year>/<month>/<post title slug>. If we wanted a route that would match that general path pattern made against both same- and cross-origin requests, using a regular expression with a wildcard (.+) at the start is one approach:

因为这可能会很尴尬,我们已经开始鼓励人们使用 callback functions 作为标准:

registerRoute(
  ({url}) => url.pathname.includes('/api/'),
  new NetworkOnly({
    plugins: [bgSyncPlugin]
  }),
  'POST'
);